[英]replace string after each second occurence of character
使用javascript變量,我想將單詞的每次出現(在示例中:“ OR”替換為||-符號),但前提是它不會出現在雙引號字符串中。
是否可以使用正則表達式 ?
我正在查看的示例:
'one OR " two OR " OR three OR five OR " OR six "'.replace( regex , ???) is giving
'one || " two OR " || three || five || " OR six "'
我嘗試過:
regex = new RegExp("([^\"]*)(OR?)([^\"]*\"[^\"]*\")" , "gi");
text = text.replace( regex , "$1||$3");
結果:
'one || " two OR " OR three OR five || " OR six "'
剩下一些需要替換的OR。
如果我嘗試再進行一次替換以擺脫剩余的OR,則替換確實(當然)不起作用:
'||ne || " two OR " OR three || five || " OR six "'
“ one”中的字母“ o”已替換為||符號,這不是故意的!
是否可以使用regExp?
好的,您要使用正則表達式嗎? 我會給你正則表達式:
var str = 'one OR " two OR " OR three OR five OR " OR six "';
var res = str.replace(/OR/g, '||');
console.log(res.replace(/(.*?)(\".*?)\|\|(.*?\")/g, '$1$2OR$3'));
享受麥迪!
與其嘗試使用單個正則表達式,不如將其分解為工作:
spl = text.split(/(".*?")/);
result = "";
spl.forEach(function (piece) {
if (~piece.indexOf('"')) {
result += piece;
}
else {
result += piece.replace("OR", "||");
}
});
用這個:
var str = 'one OR " two OR " OR three OR five OR " OR six "';
var res = str.replace(/or/gi,"||");
這將替換全部or
不區分大小寫的單詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.