jabbawabba
jabbawabba

Reputation: 69

Replace character in string with another string?

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

Answers (2)

salezica
salezica

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

thefourtheye
thefourtheye

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

Related Questions