2

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?

2
  • your code is invalid, try l < l.length Commented Feb 16, 2014 at 13:21
  • the variable 'length' is defined before the for loop Commented Feb 16, 2014 at 13:23

2 Answers 2

3

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")
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.