根據一條線:
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', '');
如何替代所有事件?
当前回答
'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
其他回答
与常规表达的i旗案例不敏感
console.log('App started'.replace(/a/g, '')) // Result: "App strted"
console.log('App started'.replace(/a/gi, '')) // Result: "pp strted"
你可以尝试这样:
示例数据:
var text = "heloo,hai,hei"
text = text.replace(/[,]+/g, '')
或
text.forEach((value) => {
hasil = hasil.replace(',', '')
})
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>
我在“图书馆”部分中添加了下面的功能到这个性能测试页面:
首頁 〉外文書 〉文學 〉文學 〉WEB
function _replace(t, s, r){
var i = t.indexOf(s);
if (i == -1) return t;
return t.slice(0, i) + r + _replace(t.slice(i + s.length, t.length), s,r);
}
把它当作测试:
var replaced = _replace(testString, 'abc', '123');
想法的一部分是,如果链条不太大,它可能会在CPU存储库中结束;通过它并粘贴它的碎片将这些比特放入存储库中,然后搜索可以完全使用CPU存储数据运行。
这不是尽可能快的,但它是尽可能快的,我可以管理没有可转换的线条. 在JavaScript中的线条可能有一个指标每个元素,因此,一个解决方案涉及很多线条元素是不可能像CPU缓存友好。
要取代所有类型的字符,请尝试此代码:
假设我们需要发送“和 \ 在我的行中,然后我们将转换“到“和 \ 到“。
因此,这种方法将解决这个问题。
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
var message = $('#message').val();
message = message.replaceAll('\\', '\\\\'); /*it will replace \ to \\ */
message = message.replaceAll('"', '\\"'); /*it will replace " to \\"*/
我使用Ajax,我需要在JSON格式发送参数,然后我的方法看起来如下:
function sendMessage(source, messageID, toProfileID, userProfileID) {
if (validateTextBox()) {
var message = $('#message').val();
message = message.replaceAll('\\', '\\\\');
message = message.replaceAll('"', '\\"');
$.ajax({
type: "POST",
async: "false",
contentType: "application/json; charset=utf-8",
url: "services/WebService1.asmx/SendMessage",
data: '{"source":"' + source + '","messageID":"' + messageID + '","toProfileID":"' + toProfileID + '","userProfileID":"' + userProfileID + '","message":"' + message + '"}',
dataType: "json",
success: function (data) {
loadMessageAfterSend(toProfileID, userProfileID);
$("#<%=PanelMessageDelete.ClientID%>").hide();
$("#message").val("");
$("#delMessageContainer").show();
$("#msgPanel").show();
},
error: function (result) {
alert("message sending failed");
}
});
}
else {
alert("Please type message in message box.");
$("#message").focus();
}
}
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};