[英]Break out of replace global loop
我有一個RegExp,用全局集進行字符串替換。 我只需要一個替換,但我使用全局,因為有第二組模式匹配(一個確定替換開始的可接受索引的數學方程式),我不能輕易表達為正則表達式的一部分。
var myString = //function-created string
myString = myString.replace(myRegex, function(){
if (/* this index is okay */){
//!! want to STOP searching now !!//
return //my return string
} else {
return arguments[0];
//return the string we matched (no change)
//continue on to the next match
}
}, "g");
如果可能的話,我如何打破字符串全局搜索?
謝謝
可能解決方案
一個解決方案(出於性能原因在我的場景中不起作用,因為我有非常大的字符串,有數千個可能的匹配到非常復雜的RegExp運行數百或數千次):
var matched = false;
var myString = //function-created string
myString = myString.replace(myRegex, function(){
if (!matched && /* this index is okay */){
matched = true;
//!! want to STOP searching now !!//
return //my return string
} else {
return arguments[0];
//return the string we matched (no change)
//continue on to the next match
}
}, "g");
請改用RegExp.exec()
。 由於您只進行一次替換,我會利用這一事實來簡化替換邏輯。
var myString = "some string";
// NOTE: The g flag is important!
var myRegex = /some_regex/g;
// Default value when no match is found
var result = myString;
var arr = null;
while ((arr = myRegex.exec(myString)) != null) {
// arr.index gives the starting index of the match
if (/* index is OK */) {
// Assign new value to result
result = myString.substring(0, arr.index) +
/* replacement */ +
myString.substring(myRegex.lastIndex);
break;
}
// Increment lastIndex of myRegex if the regex matches an empty string
// This is important to prevent infinite loop
if (arr[0].length == 0) {
myRegex.lastIndex++;
}
}
此代碼表現出與String.match()
相同的行為,因為如果最后一個匹配為空 ,它也會將索引遞增1以防止無限循環。
我質疑你關於表現的邏輯。 我認為評論中提出的一些觀點是有效的。 但是,我知道什么......;)
但是,這是做你想做的事情的一種方式。 再一次,我認為這一點,表現明智,不是最好的......:
var myString = "This is the original string. Let's see if the original will change...";
var myRegex = new RegExp('original', 'g');
var matched=false;
document.write(myString+'<br>');
myString = myString.replace(myRegex, function (match) {
if ( !matched ) {
matched = true;
return 'replaced';
} else {
return match;
}
});
document.write(myString);
這很像你的“可能的解決方案”。 並且它在替換后不會“中止”(因此我的表現保留)。 但它符合你的要求。 它取代了第一個實例,設置了一個標志,之后只返回匹配的字符串。
看到它在這里工作。
問候。
您可以放置try-catch並使用undeclared變量來退出replace函數
var i = 0;
try{
"aaaaa".replace ( /./g, function( a, b ){
//Exit the loop on the 3-rd iteration
if ( i === 3 ){
stop; //undeclared variable
}
//Increment i
i++
})
}
catch( err ){
}
alert ( "i = " + i ); //Shows 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.