admin管理员组

文章数量:1405393

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? bees Hello, how xre you? and Greetings and salutations bees Greetings and sxlutations.

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? bees Hello, how xre you? and Greetings and salutations bees Greetings and sxlutations.

Share Improve this question asked Jan 13, 2016 at 2:32 user3856347user3856347 3
  • 1 See developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – guest271314 Commented Jan 13, 2016 at 2:36
  • 1 String.prototype.replace does exactly this. ex: ('halp me plase').replace('a', 'x') === 'hxlp me plase' – PitaJ Commented Jan 13, 2016 at 2:39
  • See w3schools./jsref/jsref_replace.asp with javascript or jquerybyexample/2012/07/jquery-replace-strings.html with Jquery – Willie Cheng Commented Jan 13, 2016 at 2:44
Add a ment  | 

4 Answers 4

Reset to default 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')

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")

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>

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;
    }

本文标签: Replacing specific characters in a stringJavaScriptStack Overflow