Also consider .replace(/\*\*\*/g, '0') if you want to replace multiple occurrences of ***. (The below code only replaces the first occurrence in each string.)
stuff= ["uyuuyu", "76gyuhj***", "uiyghj", "56tyg", "juijjujh***"];
for(var i = 0; i < stuff.length; i++)
{
stuff[i] = stuff[i].replace('***', '0');
}
console.log(stuff);
Note that there's no need to check indexOf. If the substring isn't present, the replace just doesn't change anything, so you can just apply the replace to every string.
Also consider .replace(/\*\*\*/g, '0') if you want to replace multiple occurrences of ***. (The below code only replaces the first occurrence in each string.)
stuff= ["uyuuyu", "76gyuhj***", "uiyghj", "56tyg", "juijjujh***"];
for(var i = 0; i < stuff.length; i++)
{
stuff[i] = stuff[i].replace('***', '0');
}
console.log(stuff);
Note that there's no need to check indexOf. If the substring isn't present, the replace just doesn't change anything, so you can just apply the replace to every string.
you can use javascript map as below
var newStuff = stuff.map(function(item,index){
return item.replace('***','0')
});
console.log(newStuff) //["uyuuyu", "76gyuhj0", "uiyghj", "56tyg", "juijjujh0"]
es2015 (es6) with arrow function
var newStuff = stuff.map(item => item.replace('***','0'));
javascript - Replace characters in an Array - Stack Overflow
How to replace a letter in an array?
javascript - Replace character in array of objects - Stack Overflow
Replace certain character on string from an array of string in javascript - Stack Overflow
Both your methods (setCharAt and replaceAt) are returning the result, which means you have to set it:
function delCookie() {
cookies.splice(0,1);
cookies[0] = cookies[0].replaceAt(8, "Z");
//or
// cookies[0] = setCharAt(cookies[0], 8, "Z");
}
The "setCharAt" function doesn't actually alter the string passed in - it returns a new string with the appropriate character changed. In order to get the behavior you want, you'll have to replace the old string in your array with the new one.
I am creating an object letters which will get all the letters as the key and the value is an array with all the index of the letter in the word.
eg: The word hey will have the object like
{
"h":[0],
"e":[1],
"y":[2]
}
I am using Array#map() to create an array of stars.
To know where to put the letter instead of a star I am using Array#find() to find the key with the letter typed. If the result is undefined - it means that the letter you tried is not in the word. If it is defined, I replace the star at the index of the letter with the correct letter
$(document).ready(function() {
$('#div_letter').hide();
var word_input = $('#word');
var word_array = [];
var letters = {};
word_input.keypress(function(e) {
if (e.keyCode == 13) {
word_array = Array.from(word_input.val());
letters = word_array.reduce((obj,letter, i)=>{
obj[letter] = obj[letter] || [];
obj[letter].push(i);
return obj;
}, {});
var stars = word_array.map(l=>"*");
$('#div_word').hide();
$('#div_letter').show();
$('#display').text(stars.join(""));
$('#letter').keypress(function(e) { //if any key is pressed
var _letter = $(this);
var char = String.fromCharCode(e.which).toLowerCase(); //get which key
let keyLetter = Object.keys(letters).find(l=>l.toLowerCase()===char);
if(keyLetter){
letters[keyLetter].forEach(i=>stars[i] = char);
$('#display').text(stars.join(""));
}
_letter.val("");
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="div_word">
<label>Enter your Word</label>
<input id="word" type="text"><br>
</div>
<div id="div_letter">
<label>Type a letter</label>
<input id="letter" type="text" /><br>
</div>
<label>Display Array:</label>
<div id="display">
</div>
I just turned the word into a dictionary, then used that to determine where in the mask to replace a character.
I have purposely left out the user interaction code as that is surplus to the requirements.
See working plnkr
var word = "milly";
var mask = '*'.repeat(word.length);
var dict = word
.split('')
.map((m, i) => ({ letter: m, index: i }))
.reduce((f, c) => {
if (f[c.letter]) {
f[c.letter] = [f[c.letter], c.index];
return f;
}
return Object.assign({}, f, {[c.letter]: c.index})
}, {});
console.log(dict); // Object {m: 0, i: 1, l: Array[2], y: 4}
var input = "l";
function revealLetter(input, mask, dict) {
var ind = dict[input];
if (ind !== undefined && ind instanceof Array) {
mask = ind.reduce((f, i) => changeCharacter(f, i, input), mask);
} else {
mask = changeCharacter(mask, ind, input);
}
return mask;
}
function changeCharacter(mask, ind, input) {
return mask.split('').map((s, i, o) => i === ind ? input : o[i]).join('');
}
mask = revealLetter(input, mask, dict);
console.log(mask); // **ll*
Just used a few map reduces. You know when you need to use reduce, because you'll have an array and you'll want a single value back.
If there is anything you want explicitly clarifying just say - but the logs easily show what happens at each stage.
One option is to stringify the object, replace, then parse it:
const testArray = [
{ ASIN: 'ABC123', Rank: '£50', Sales: '£80' },
{ ASIN: 'ZYX123&', Rank: '£70', Sales: '£20' },
];
const newTestArray = JSON.parse(
JSON.stringify(testArray).replaceAll('£', '')
);
console.log(newTestArray);
Could also transform the object by mapping with Object.fromEntries:
const testArray = [
{ ASIN: 'ABC123', Rank: '£50', Sales: '£80' },
{ ASIN: 'ZYX123&', Rank: '£70', Sales: '£20' },
];
const newTestArray = testArray.map(
obj => Object.fromEntries(
Object.entries(obj)
.map(([key, val]) => [key, val.replaceAll('£', '')])
)
);
console.log(newTestArray);
If you want to replace characters only in the values of the objects in array, you can try following code. It will iterate each object of the array one by one, get all keys of that object and iterate over those keys to replace the character in their values.
let keys;
testArray.map((obj)=>{
keys = Object.keys(obj);
keys.map((val)=>{
obj[val].replace(/a/g, "b");
})
})
You could globally match ___ using the /g flag and get the index of the replacement from blankData be seeding a start value of 0 and increment it in every iteration.
const text = 'hello ___ where ___ test ___';
const blankData = ['there', 'you', 'it'];
result = text.replace(/___/g, (i => _ => blankData[i++])(0));
console.log(result);
Note that if you don't want to have multiple matches for _________ but also don't want to match a single _ you can use _{3,} as the pattern to match 3 or more times an underscore.
const text = 'h_ello ______ where ___ test ___';
const blankData = ['there', 'you', 'it'];
result = text.replace(/_{3,}/g, (i => _ => blankData[i++])(0));
console.log(result);
I already made a function for that. I think the code is self-explanatory.
function injectStrings(string, replacementsArr) {
var pattern = /___/g,
replacement = '';
return string.replace(pattern, function(match) {
replacement = replacementsArr.shift();
if (typeof replacement == 'number' || typeof replacement == 'string') {
return replacement;
}
// console.log('parameter for ' + match + ' is missing in \"' + string + '\"');
return '';
});
}
const text = 'hello ___ where ___ test ___'
const blankData = ['there', 'you', 'it']
// output: And also an array like this
console.log( injectStrings(text, blankData) );
This should work.
let names = ["Fern", "Alexa", "Constance", "Daniella", "Connie", "Flora", "Hannah", "Maddie"];
let modified = names.map(e => e.replace(e[0], 'B'))
console.log(modified);
Iterate with for of loops to access each item and then apply replace method.
var names = ["Fern","Alexa","Constance","Daniella","Connie","Flora","Hannah","Maddie"];
var newNames = [];
for(let el of names) {
newNames.push(el.replace(el[0], 'B'));
}
console.log(newNames);
You can try this code:
a = "{12,a},b,c,{c,d}";
m = a.match(/{[^}]*}|[^,]+/g);
arr=[];
for (i=0; i<m.length; i++) {
if (m[i].indexOf('{') >= 0)
arr.push(m[i].replace(/[{}]/g, "").split(/,/));
else
arr.push(m[i]);
}
console.log(arr);
OUTPUT:
[[12,a],b,c,[c,d]]
could you try this .
var m = "{12,a},b,c,{c,d}".split(','),
result = m.reduce( function( a, b) {
if ( b.indexOf('{') !== -1 || a.t.length ){
a.t.push( b.replace(/\{|\}/,'') );
} else {
a.array.push( b );
}
if ( b.indexOf('}') !== -1 ){
a.array.push( a.t );
a.t = [];
}
return a ;
}, { array:[],t:[]} ).array;
console.log( result );
Use String.replace() with a function that generates the replacement string. In the function get the current replacement from newWords using a counter:
function replaceAsterisk(sentence, newWords) {
let counter = 0;
return sentence.replace(/\*/g, () => newWords[counter++] || '');
}
console.log(replaceAsterisk("My name is * and I am a *.", ["Sabrina", "Black Cat", "extra", "words"]));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You have to loop through all the characters first, see below the example.
function replaceAsterisk(sentence, newWords) {
let newArray = [];
let character = sentence.split("");
console.log(character);
character.forEach(function(c){
// if the character is not an asterisk, push it into the new array
if (c !== "*") {
newArray.push(c);
}
// if the character is an asterisk, push "cat" into the new array
else {
newArray.push("cat");
}
});
// return new array as a string
return newArray.join("");
}
console.log(replaceAsterisk("My name is * and I am a *.", ["Sabrina", "Black Cat", "extra", "words"]));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You need to use a regular expression with the global option set to replace all of the instances. But, you can also simplify this code a bit and get rid of the loop. Instead of Arrays, use an object:
var alphabet = {
'a': 'ⴰ',
'b': 'ⴱ',
'g': 'ⴳ',
'gw': 'ⴳⵯ',
'd': 'ⴷ',
'ḍ': 'ⴹ',
...
'z': 'ⵣ',
'ẓ': 'ⵥ'
};
Then use a regular expression with a replacement function:
var word = $("input[name=word]").val();
var tifinaghized = word.replace(/[abgdḍefkhḥɛxqijlmnurṛɣsṣctṭwYzẓ]|gw|kw/g, function(s) {
return alphabet[s];
});
Working demo: http://jsfiddle.net/gilly3/MdF6R/
If you change:
tifinaghized += word.replace(word_split, alphabet[i][1]);
to use regular expressions:
tifinaghized += word.replace(new RegExp(word_split, 'g'), alphabet[i][1]);
the g will find all occurrences.
Yes.
for(var i=0; i < arr.length; i++) {
arr[i] = arr[i].replace(/,/g, '');
}
The best way nowadays is to use the map() function in this way:
var resultArr = arr.map(function(x){return x.replace(/,/g, '');});
this is ECMA-262 standard. If you nee it for earlier version you can add this piece of code in your project:
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
Usually, the result of the replace function is returned as a new String object in most of the programming languages. You should change your code to this:
if (name.charAt(i) === charList[j])
name = name.replace(name.charAt(i), replaceList[j]);
Also, since the replace function will replace all the occurrences of that character, you could change your algorithm a little bit.
You can put the mapping into an object, which has the advantage of being a bit easier to maintain since the character and its replacement are adjacent in the object, rather than trying to align position in an array.
e.g.
var name = "przykłąd Ęś";
// Object of characters to replace and their replacement values
var charList = {'Ą':'A', 'ą':'a', 'Ć':'C', 'ć':'c', 'Ę':'E', 'ę':'e',
'Ł':'L', 'ł':'l', 'Ó':'O', 'ó':'o', 'Ś':'S', 'ś':'s',
'Ź':'Z', 'ź':'z', 'Ż':'Z', 'ż':'z'};
// For each character in the string, search for it in charList and if found,
// replace it with the value
alert(
name + '\n' + name.replace(/./g, function(c) {return c in charList? charList[c] : c})
);
There is likely something cleverer that can be done with char codes, but I can't think of it right now.
Edit 2017
Fixed last character mapping—thanks @MarekSkiba. :-)