根據一條線:
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', '');
如何替代所有事件?
当前回答
把它推到发生的数字达到0,如下:
function replaceAll(find, replace, str) {
while (str.indexOf(find) > -1) {
str = str.replace(find, replace);
}
return str;
}
其他回答
这个解决方案结合了一些以前的答案,并更好地符合建议的2020年8月标准解决方案,这个解决方案在2020年9月对我来说仍然可行,因为String.replaceAll不在我使用的Node.js二进制中。
RegExp.escape 是一个单独的问题处理,但它在这里很重要,因为官方提出的解决方案将自动逃脱基于链条的查找输入。
如果你需要准确的标准符合,对于一个应用程序,它是严格依赖于标准实施,那么我建议使用Babel或其他工具,你得到“正确的答案”每次而不是Stack Overflow。
代码:
if (!Object.prototype.hasOwnProperty.call(RegExp, 'escape')) {
RegExp.escape = function(string) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
// https://github.com/benjamingr/RegExp.escape/issues/37
return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
};
}
if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
String.prototype.replaceAll = function(find, replace) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
// If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
// TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
// String parameters to 'find' do not require special handling.
// Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
// Does not conform to "Specifying a function as a parameter" for replace
return this.replace(
Object.prototype.toString.call(find) == '[object RegExp]' ?
find :
new RegExp(RegExp.escape(find), 'g'),
replace
);
}
}
编码,小型:
Object.prototype.hasOwnProperty.call(RegExp,"escape")||(RegExp.escape=function(e){return e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}),Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(RegExp.escape(e),"g"),t)});
例子:
console.log(
't*.STVAL'
.replaceAll(
new RegExp(RegExp.escape('T*.ST'), 'ig'),
'TEST'
)
);
console.log(
't*.STVAL'
.replaceAll(
't*.ST',
'TEST'
);
);
没有 RegExp.Escape 的代码:
if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
String.prototype.replaceAll = function(find, replace) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
// If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
// TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
// String parameters to 'find' do not require special handling.
// Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
// Does not conform to "Specifying a function as a parameter" for replace
return this.replace(
Object.prototype.toString.call(find) == '[object RegExp]' ?
find :
new RegExp(find.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'), 'g'),
replace
);
}
}
代码没有 RegExp.Escape,小型:
Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&"),"g"),t)});
2019年11月,新功能被添加到JavaScript, string.prototype.replaceAll()。
目前它仅支持巴比伦,但也许在未来它可以在所有浏览器中实施。
从 v85 开始,Chrome 现在支持 String.prototype.replaceAll 原始。 请注意,这一点超越了所有其他提议的解决方案,并且应该使用一次主要支持。
功能状态: https://chromestatus.com/feature/6040389083463680
var s = “Hello hello world”; s = s.replaceAll(“Hello”,“”); // s 现在是“世界” console.log(s)
String.prototype.replace 所有()
如果你不想处理替代() + RegExp。
但是,如果浏览器在2020年之前?
我推荐的替代All polyfill的选项:
替代All polyfill (与全球旗帜错误) (更多原则版)
if (!String.prototype.replaceAll) { // Check if the native function not exist
Object.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) String
configurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)
value: function(search, replace) { // Set the function by closest input names (For good info in consoles)
return this.replace( // Using native String.prototype.replace()
Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?
? search.global // Is the RegEx global?
? search // So pass it
: function(){throw new TypeError('replaceAll called with a non-global RegExp argument')}() // If not throw an error
: RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExp
replace); // passing second argument
}
});
}
替代All polyfill (With handling global-flag missing by itself) (我的第一个偏好) - 为什么?
if (!String.prototype.replaceAll) { // Check if the native function not exist
Object.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) String
configurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)
value: function(search, replace) { // Set the function by closest input names (For good info in consoles)
return this.replace( // Using native String.prototype.replace()
Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?
? search.global // Is the RegEx global?
? search // So pass it
: RegExp(search.source, /\/([a-z]*)$/.exec(search.toString())[1] + 'g') // If not, make a global clone from the RegEx
: RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExp
replace); // passing second argument
}
});
}
小型(我的第一个偏好):
if(!String.prototype.replaceAll){Object.defineProperty(String.prototype,'replaceAll',{configurable:!0,writable:!0,enumerable:!1,value:function(search,replace){return this.replace(Object.prototype.toString.call(search)==='[object RegExp]'?search.global?search:RegExp(search.source,/\/([a-z]*)$/.exec(search.toString())[1]+'g'):RegExp(String(search).replace(/[.^$*+?()[{|\\]/g,"\\$&"),"g"),replace)}})}
其他方法的聚合物分配
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(search, replace) { // <-- Naive method for assignment
// ... (Polyfill code Here)
}
}
for (var k in 'hi') console.log(k);
// 0
// 1
// replaceAll <-- ?
非常可靠,但重
事实上,我提出的选项有点乐观,正如我们信任环境(浏览器和Node.js),它肯定是2012年至2021年左右。
此分類上一篇: HTTPS://polyfill.io
特别是替代:
<script src="https://polyfill.io/v3/polyfill.min.js?features=String.prototype.replaceAll"></script>
以前的答案太复杂了,只需使用替代功能如下:
str.replace(/your_regex_pattern/g, replacement_string);
例子:
var str = “测试 abc 测试 abc 测试 abc 测试 abc”; var res = str.replace(/[abc]+/g, ""); console.log(res);