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
.
- 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
4 Answers
Reset to default 2for 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
版权声明:本文标题:Replacing specific characters in a string - JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744235634a2596540.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论