我的代码就是这样..
function replaceAll(str, from, to) {
let result = ''
for(let i = 0 ; i < str.length ; i++)
if(str[i]===from) {
result = str.replace(from,to)
}
}
return result;
}
我想就这样回来
let output = replaceAll('loop', 'o', 'e');
console.log(output); // --> 'leep'
但它只是改变了'leop'
答案 0 :(得分:3)
您可以在 JavaScript 中使用 replaceAll()
函数。
const str = 'loop';
console.log(str.replaceAll('o', 'e'));
答案 1 :(得分:3)
您可以通过两种方式解决您的问题:
/…/g
) 的 replace
函数(每个浏览器都支持)替换所有出现的内容replaceAll
函数(Chrome 85+、Edge 85+、Firefox 77+、Opera 71+、Safari 13.1+ 支持;Internet Explorer 不支持)let str = 'loop';
console.log(str.replace(/o/g, 'e'));
console.log(str.replaceAll('o', 'e'));
答案 2 :(得分:1)
为什么?
简单替换只替换第一个匹配的文本。所以你需要使用g
-全局文本匹配模式。但是你是从文本作为变量传递的。所以使用 RegExp
来创建像
function replaceAll(str, from, to) {
return str.replace(RegExp(from,'g'),to)
}
let output = replaceAll('loop', 'o', 'e');
console.log(output); // --> 'leep'
答案 3 :(得分:1)
它会告诉您为什么它不起作用。
function replaceAll(str, from, to) {
let result = str;
for(let i = 0 ; i < str.length ; i++) {
if(str[i]===from) {
result = result.replace(from,to);
}
}
return result;
}
答案 4 :(得分:1)
如果你真的想循环,你需要将替换后的字符串赋值给str
而不是result,因为你取的是原来的str
进行替换,而是赋值给result
.
String#replace
仅替换字符串的第一个查找。如果使用正则表达式,则可以直接替换所有出现次数。
function replaceAll(str, from, to) {
for (let i = 0; i < str.length; i++) {
if (str[i] === from) {
str = str.replace(from, to);
}
}
return str;
}
let output = replaceAll('loop', 'o', 'e');
console.log(output); // --> 'leep'
答案 5 :(得分:1)
让我们更深入地了解您的问题,以便您了解这里的实际情况
function replaceAll(str, from, to) {
let result = ''
for(let i = 0 ; i < str.length ; i++)
if(str[i]===from) {
result = str.replace(from,to)
}
}
return result;
}
str
是字符串类型变量。字符串数据类型是值类型。当您更改字符串中的字符时,它不会重写初始变量的内容。而是创建一个新的字符串值并将其存储到内存中。之前的值被垃圾收集。
最初是 str == loop
,现在如果您先将 'o'
更改为 'e'
,那么 str
仍然是“循环”。将新数据分配给 result
变量,该变量保存值 'leop'
。这就是为什么在您的 for 循环中总是将相同的值分配给结果变量。
让我们将过程可视化:
1st iteration :
result = 'loop'.replace('o','e') // leop
// result is now 'leop' and str remains 'loop'
2nd iteration :
result = 'loop'.replace('o','e') // leop
// as str remained 'loop', so result will again be 'leop
这就是为什么 result
变量在 for 循环完成后保持不变的原因。
另一件需要注意的事情,虽然在第一次和第二次迭代中,result
变量的值是相同的('leop'
),但是在第二次循环中,第一次循环的初始 'leop'
是 {{ 1}} 以便为其分配另一个值(在我们的示例中为另一个 gurbage collected (thrown away)
)