[英]JavaScript Bracket RegExp
我想用“ad231-3213-e12211”替換這個:“[ID]”
我正在使用這個正則表達式: /\\[ID\\]/i
它與.replace(/\\[ID\\]/i, id)
完美配合.replace(/\\[ID\\]/i, id)
現在我將它封裝在這個函數中:
self.changeUrl = function (url, id, replaceExp) {
replaceExp = replaceExp === 'undefined' ? new RegExp("\[ID\]") : replaceExp instanceof RegExp ? replaceExp : new RegExp("\[ID\]"); // basically ensure that this is a regexp
return url.replace(replaceExp, id);
};
還有這個:
self.changeUrl = function (url, id, replaceExp) {
replaceExp = replaceExp === 'undefined' ? new RegExp("\u005BID\u005D") : replaceExp instanceof RegExp ? replaceExp : new RegExp("\u005BID\u005D"); // basically ensure that this is a regexp
return url.replace(replaceExp, id);
};
它們都不起作用,我錯過了什么?
由於您將字符串傳遞給RegExp
構造函數,因此您還需要轉義字符串中的\\
字符。 因此,使用\\\\[
實際上將成為\\[
在字符串變量中; 而\\[
將成為[
僅。
new RegExp( "\\[ID\\]" )
為了確定:
如果要替換像[ID]
這樣的固定子字符串,根本不需要正則表達式,您可以簡單地寫:
self.changeUrl = function (url, id, replaceExp) {
return (replaceExp instanceof RegExp) ? url.replace(replaceExp, id)
: url.replace('[ID]', id);
};
要么
self.changeUrl = function (url, id, replaceExp) {
return (replaceExp === 'undefined') ? url.replace('[ID]', id)
: url.replace(replaceExp, id);
};
(取決於你想要的行為)
"\\[ID\\]"
- 這基本上將正則表達式轉換為[ID]
因為JavaScript中的反斜杠用作轉義字符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.