在本网站上查阅多个答案后,我仍然无法找到如何在Javascript中替换字符串中的某些字符的解决方案。我尝试使用正则表达式的.replace()无效。
就上下文而言,这就是我所拥有的:
var text = document.getElementById('text');
var button = document.getElementById('myBtn');
button.onclick = function() {
var splitter = text.value.split(" ");
for(var i=0; i < splitter.length; i++) {
if(splitter[i].match("er$")) {
splitter[i].replace(/er$/, "x"); <----The one line causing me insanity.
}
}
答案 0 :(得分:2)
javascript中的字符串是不可变的,因此replace会返回一个新字符串。
你可能想要
splitter[i] = splitter[i].replace(/er$/, "x");
另请注意,您不必测试之前是否匹配,并且您可以在不拆分的情况下执行整个操作(通过\b
使用此正则表达式的字边界:/er\b/g
)
答案 1 :(得分:0)
你可以在这里描述这个技术:
How do I replace a character at a particular index in JavaScript?
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
并使用如下
var hello="Hello World";
alert(hello.replaceAt(3, "a"));