1

Okay, so I'm trying to create a JavaScript function to replace specific characters in a string. What I mean by this is, lets say, searching a string character by character for a letter and if it matches, replacing it with another character. Ex, replacing "a" with "x": Hello, how are you? becomes Hello, how xre you? and Greetings and salutations becomes Greetings and sxlutations.

3

4 Answers 4

2

for removing multiple characters you could use a regex expression

yourString.replace(new RegExp('a', 'g'), 'x')

for removing the same with a case-insensitive match use

yourString.replace(new RegExp('a', 'gi'), 'x')
Sign up to request clarification or add additional context in comments.

Comments

1

As String.replace() does not seem to fullfil the OPs desires, here is a full function to do the stuff the OP asked for.

function rep(s,from,to){
  var out = "";
  // Most checks&balances ommited, here's one example
  if(to.length != 1 || from.length != 1)
    return NULL;

  for(var i = 0;i < s.length; i++){
    if(s.charAt(i) === from){
      out += to;
    } else {
      out += s.charAt(i);
    }
  }
  return out;
}

rep("qwertz","r","X")

Comments

1

var s1 = document.getElementById('s1').innerHTML;
var s2 = s1.replace('a', 'x');
document.getElementById('s2').innerHTML = s2;
<h1>Starting string:</h1>
<p id="s1">Hello, how are you?</p>

<h1>Resulting string:</h1>
<p id="s2"></p>

Comments

1

Here is a simple utility function that will replace all old characters in some string str with the replacement character/string.

    function replace(str, old, replacement) {
        var newStr = new String();
        var len = str.length;
        for (var i = 0; i < len; i++) {
            if (str[i] == old)
                newStr = newStr.concat(replacement);
            else
                newStr = newStr.concat(str[i]);                  
        }
        return str;
    }

Comments

Your Answer

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