- QUESTION -
In my Meteor app, I have an array of objects with the following structure
[{ type: "oldValue" }]
When I run
testArray[0].type = 'test'
console.log(testArray[0].type)
'test'
is correctly printed in the console. However, when I runtestArray[0].type[1] = 'd'
console.log(testArray[0].type)
'test'
is printed in the console instead of 'tdst'
. The second letter wasn't changed to a d
.
How can I change individual characters within a string?
- ANSWER -
As @Pointy pointed out, strings are immutable. If you want to change certain characters, you can work with an array of characters:
var myString = 'hello there!'
myString = myString.split('')
myString[1] = 'a'
myString = myString.join('')
console.log(myString) // 'hallo there!'
However, per your comment, you probably want to iterate through the string once, since constantly splitting and joining the string might be slow:
function replaceCharacters (str, chars, conversionFunction) {
var charBuff = []
for (var i = 0; i < str.length; i++) {
if (chars.indexOf(str[i])) {
charBuff.push(conversionFunction(str[i]))
} else {
charBuff.push(str[i])
}
}
return charBuff.join('')
}
examples:
console.log(replaceCharacters('hello', 'al', function (myChar) { return 'Z' }))
// logs 'heZZo'
// you can pass an array or a string as the second parameter
// since `.indexOf` works on both strings and arrays
and if you're working with es6:
function replaceCharacters (str, chars, conversionFunc) {
return [...str].reduce((p, c) => {
p.push(chars.indexOf(c) === -1 ? c : conversionFunc(c))
return p
}, []).join('')
}
0 comments:
Post a Comment