Reputation: 69
I'm having trouble replacing characters in a string.
Here's the code I currently have:
var entry_value = document.getElementById("entry_box").value;
var length = entry_value.length;
for(var l = 0; l < length; l += 1) {
letter = encoded[l]
encoded = entry_value.replace(letter, "b")
}
This will only replace the first instance of letter
with b
, my question is how do I replace every instance of letter
throughout the string?
Upvotes: 2
Views: 106
Reputation: 76929
You need to use a global regular expression instead of a string as pattern:
"aaaa".replace("a", "b") // "baaa"
"aaaa".replace(/a/g, "b") // "bbbb"
Try this:
encoded = entry_value.replace(new RegExp(letter, "g"), "b")
Upvotes: 3
Reputation: 239473
You can simply do
entry_value = entry_value.split(letter).join("b");
For example,
var entry_value = "abcdcfchij";
entry_value = entry_value.split("c").join("b");
console.log(entry_value); // abbdbfbhij
Upvotes: 3