我的代码:
function removeFromString(mystring,char){
let regex = new RegExp(char, 'g');
let string;
for(let i; i< mystring.length; i++){
string = mystring.replace(regex, ''));
}
console.log(mystring);
}
removeFromString('Hello How are you','o');
这行不通。 知道我做错了什么吗?
最佳答案
方法String.replace()
不会更改字符串,它会创建一个新字符串。返回替换的结果。
此外,由于您在正则表达式中使用了 g
标志,它将替换字符串中所有出现的地方,因此您不需要 for 循环。
function removeFromString(mystring, char) {
const regex = new RegExp(char, 'g');
return mystring.replace(regex, '');
}
console.log(removeFromString('Hello How are you', 'o'));
你也可以用循环实现同样的事情,通过从原始字符串中的所有字符重建字符串,而不是 char
:
function removeFromString(mystring, char) {
let string = '';
for (let i = 0; i < mystring.length; i++) {
if(mystring[i] !== char) string += mystring[i];
}
return string;
}
console.log(removeFromString('Hello How are you', 'o'));
关于javascript - 如何从字符串中删除所有出现的任何给定字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50108595/