根據一條線:
s = "Test abc test test abc test test test abc test test abc";
这似乎只是在上面的行中删除ABC的第一次出现:
s = s.replace('abc', '');
如何替代所有事件?
根據一條線:
s = "Test abc test test abc test test test abc test test abc";
这似乎只是在上面的行中删除ABC的第一次出现:
s = s.replace('abc', '');
如何替代所有事件?
当前回答
试试这:
String.prototype.replaceAll = function (sfind, sreplace) {
var str = this;
while (str.indexOf(sfind) > -1) {
str = str.replace(sfind, sreplace);
}
return str;
};
其他回答
把它推到发生的数字达到0,如下:
function replaceAll(find, replace, str) {
while (str.indexOf(find) > -1) {
str = str.replace(find, replace);
}
return str;
}
这可以用常规表达式和旗帜g来解决,这意味着在找到第一场比赛后不停止。
function replaceAll(string, pattern, replacement) {
return string.replace(new RegExp(pattern, "g"), replacement);
}
// or if you want myString.replaceAll("abc", "");
String.prototype.replaceAll = function(pattern, replacement) {
return this.replace(new RegExp(pattern, "g"), replacement);
};
可替代的独特价值
String.prototype.replaceAll = function(search_array, replacement_array) { // var target = this; // search_array.forEach(function(substr, index) { if (typeof replacement_array[index]!= "undefined") { target = target.replace(new RegExp(substr, 'g'), replacement_array[index] ) }); // return target; }; // Use: var replacedString = "This topic commented o
我喜欢这个方法(看起来有点干净):
text = text.replace(new RegExp("cat","g"), "dog");
试试这:
String.prototype.replaceAll = function (sfind, sreplace) {
var str = this;
while (str.indexOf(sfind) > -1) {
str = str.replace(sfind, sreplace);
}
return str;
};