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.
4 Answers
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
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; }
String.prototype.replacedoes exactly this. ex:('halp me plase').replace('a', 'x') === 'hxlp me plase'