Here is a Codepen version。怪異的行爲與正則表達式匹配
我的目標是遍歷數組的元素,搜索匹配[email protected]
的東西@~
,刪除標識匹配的那些「書擋」,然後.join()
數組。在下面的例子中,結果應該看起來像a/b/c
。
但是相反,我得到的結果a/[email protected]@~/c
。爲了讓事情更加令人困惑,當我顛倒數組元素的順序時,問題結果從[email protected]@~
變爲[email protected]@~
。最後,把事情非常怪異,這個問題似乎通過把一個簡單test
方法,它本身總是返回false
值自行解決。查看代碼中的評論。親眼看看。
是什麼原因造成這種奇怪的行爲?迭代這些元素並執行我描述的替換的正確方法是什麼?
function myFunction() {
var a = ["a", "[email protected]@~", "[email protected]@~"]
var re = /[email protected](.*?)@~/g;
var i = a.length;
// Uncomment below line to see the problem change from [email protected]@~ to [email protected]@~
//a.reverse();
while (i--) {
console.log('i', i, 'str', a[i]);
var match = re.exec(a[i]);
console.log('match', match);
// Uncomment the below line to see it work properly.
//console.log('test', re.test(a[i]));
if (match && match[0] && match[1]) {
a[i] = a[i].replace(match[0], match[1]);
console.log('a[i]', a[i]);
}
}
var res = a.join('/');
document.getElementById("demo").innerHTML = res;
}
<p>
My goal is to print the string: <code>a/b/c</code>. See weird <i>uncomment</i> fix in JS.
<button onclick="myFunction()">Click Here</button>
</p>
<p id="demo"></p>
是:*串插*。見下面評論接受答案。 – Mowzer