我正在尝试创建一个简单的函数来替换 JS 中字符串中某个字符的所有实例。在这种情况下,我想替换所有a
's with o
's.
我很确定代码是正确的,但输出仍然是原始字符串。
function replaceLetter(string){
for(var i = 0; i < string.length; i++){
if(string[i] == 'a'){
console.log(string[i]);
string[i] = 'o'
}
}
return string;
}
replaceLetter('hahaha') // returns 'hahaha'
为什么不把 a 换成 o 呢?
您可以使用如下正则表达式:
function replaceLetter(str) {
return str.replace(/a/g, 'o');
}
var st = replaceLetter('hahaha');
console.log(st);
或者使用另一个字符串来累积结果,如下所示:
function replaceLetter(str) {
var res = ''; // the accumulator (because string litterals are immutable). It should be initialized to empty string
for(var i = 0; i < str.length; i++) {
var c = str.charAt(i); // get the current character c at index i
if(c == 'a') res += 'o'; // if the character is 'a' then replace it in res with 'o'
else res += c; // otherwise (if it is not 'a') leave c as it is
}
return res;
}
var st = replaceLetter('hahaha');
console.log(st);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)