根據一條線:
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(find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);
};
其他回答
在最受欢迎的浏览器的最新版本中,您可以使用 ReplaceAll 如下:
let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"
但是,请检查我可以使用或其他兼容性表,首先确保您针对的浏览器首先添加了支持。
对于 Node.js 和旧/非当前浏览器的兼容性:
注意:不要在性能关键代码中使用下列解决方案。
作为一个简单的字体字符串的常规表达的替代品,您可以使用
str = "Test abc test test abc test...".split("abc").join("");
一般模式是
str.split(search).join(replacement)
这通常比在某些情况下更快,而不是使用替代所有和一个常见的表达式,但这似乎不再是现代浏览器的情况。
基准: https://jsben.ch/TZYzj
结论:
如果你有一个性能关键的使用案例(例如,处理数百条线),使用常规表达方法,但对于大多数典型的使用案例,这很好不需要担心特殊的字符。
这可以用常规表达式和旗帜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);
};
就像上面的分裂/合并解决方案一样,下面的解决方案与逃避字符没有任何问题,与常规表达方法不同。
function replaceAll(s, find, repl, caseOff, byChar) {
if (arguments.length<2)
return false;
var destDel = ! repl; // If destDel delete all keys from target
var isString = !! byChar; // If byChar, replace set of characters
if (typeof find !== typeof repl && ! destDel)
return false;
if (isString && (typeof find !== "string"))
return false;
if (! isString && (typeof find === "string")) {
return s.split(find).join(destDel ? "" : repl);
}
if ((! isString) && (! Array.isArray(find) ||
(! Array.isArray(repl) && ! destDel)))
return false;
// If destOne replace all strings/characters by just one element
var destOne = destDel ? false : (repl.length === 1);
// Generally source and destination should have the same size
if (! destOne && ! destDel && find.length !== repl.length)
return false
var prox, sUp, findUp, i, done;
if (caseOff) { // Case insensitive
// Working with uppercase keys and target
sUp = s.toUpperCase();
if (isString)
findUp = find.toUpperCase()
else
findUp = find.map(function(el) {
return el.toUpperCase();
});
}
else { // Case sensitive
sUp = s;
findUp = find.slice(); // Clone array/string
}
done = new Array(find.length); // Size: number of keys
done.fill(null);
var pos = 0; // Initial position in target s
var r = ""; // Initial result
var aux, winner;
while (pos < s.length) { // Scanning the target
prox = Number.MAX_SAFE_INTEGER;
winner = -1; // No winner at the start
for (i=0; i<findUp.length; i++) // Find next occurence for each string
if (done[i]!==-1) { // Key still alive
// Never search for the word/char or is over?
if (done[i] === null || done[i] < pos) {
aux = sUp.indexOf(findUp[i], pos);
done[i] = aux; // Save the next occurrence
}
else
aux = done[i] // Restore the position of last search
if (aux < prox && aux !== -1) { // If next occurrence is minimum
winner = i; // Save it
prox = aux;
}
} // Not done
if (winner === -1) { // No matches forward
r += s.slice(pos);
break;
} // No winner
// Found the character or string key in the target
i = winner; // Restore the winner
r += s.slice(pos, prox); // Update piece before the match
// Append the replacement in target
if (! destDel)
r += repl[destOne ? 0 : i];
pos = prox + (isString ? 1 : findUp[i].length); // Go after match
} // Loop
return r; // Return the resulting string
}
文档如下:
替代All Syntax ====== 替代All(s, find, [repl, caseOff, byChar) 参数 ==========“s” 是替代序列的目标. “find” 可以是序列或序列的序列. “repl” 应该是相同的类型“find” 或空的 如果“find” 是序列,它是一个简单的替代所有“find” 事件在“s” 由序列“repl” 如果“find” 是序列,它将取代
function l() {
return console.log.apply(null, arguments);
}
var k = 0;
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
["ri", "nea"], ["do", "fa"])); // 1
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
["ri", "nea"], ["do"])); // 2
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
["ri", "nea"])); // 3
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
"aeiou", "", "", true)); // 4
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
"aeiou", "a", "", true)); // 5
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
"aeiou", "uoiea", "", true)); // 6
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
"aeiou", "uoi", "", true)); // 7
l(++k, replaceAll("banana is a ripe fruit harvested near the river",
["ri", "nea"], ["do", "fa", "leg"])); // 8
l(++k, replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
["ri", "nea"], ["do", "fa"])); // 9
l(++k, replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
["ri", "nea"], ["do", "fa"], true)); // 10
return;
'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"
這是一個簡單的雷格斯,避免在大多數情況下取代字的部分. 然而,一個<unk> - 仍然被認為是字的邊界. 所以條件可以用在這種情況下,以避免取代線,如冷貓:
'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong
//"a dog is not a cool-dog" -- nips
'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');
//"a dog is not a cool-cat"
Regexp 不是唯一的替代多种现象的方法,远离它,思考灵活,思考分裂!
var newText = "the cat looks like a cat".split('cat').join('dog');
否则,要防止替代词部分 - 批准的答案也会做什么! 你可以通过常规的表达方式来围绕这个问题,我承认,有点复杂,并且作为一个惊喜,一个缓慢的,也:
var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
结果与接受的答案相同,但是,在这个行上使用 /cat/g 表达式:
var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');
//returns "the dog looks like a dog, not a dogerpillar or cooldog" ??
var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
//return "the dog looks like a dog, not a caterpillar or coolcat"
RegExp(常规表达式)对象 Regular-Expressions.info
在这种情况下,它显著简化表达,并提供更多的灵活性,如用正确的资本化替换或在一个行中替换两只猫和猫:
'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
.replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
{
// Check 1st, capitalize if required
var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
if (char1 === ' ' && char2 === 's')
{ // Replace plurals, too
cat = replacement + 's';
}
else
{ // Do not replace if dashes are matched
cat = char1 === '-' || char2 === '-' ? cat : replacement;
}
return char1 + cat + char2;//return replacement string
});
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar
如果使用图书馆是您的选择,那么您将获得与图书馆功能一起进行的测试和社区支持的好处。
// Include a reference to the string.js library and call it (for example) S.
str = S(str).replaceAll('abc', '').s;