[英]regexp to replace start/end symbols multiple times across the string
作為regexp的新手,我無法構造regexp來完成以下任務:
字符串:
(q[1]="one" and q[2]="two")
所需結果:
(q[1].indexOf("one") and q[2].indexOf("two"))
因此,正則表達式應將="
替換="
.indexOf("
組合,並將任何字符后跟"
替換為")
謝謝幫忙!
var str = '(q[1]="one" and q[2]="two")';
str = str.replace(/=("[^"]+")/g, '.indexOf($1)')
這將str設置為
(q[1].indexOf("one") and q[2].indexOf("two"))
嘗試這個:
var str = '(q[1]="one" and q[2]="two")'; // use let instead of var if it's available
var newstr = str.replace(/=(".+?")/g, '.indexOf($1)');
請注意,雖然我的解決方案與dystroy的解決方案幾乎相同,但它使用的正則表達式略有不同。 +?
是非貪婪匹配,意味着而不是盡可能地匹配而不是盡可能少地匹配(因此,當搜索字符串"a"b"
以進行匹配時,/”。 /".+"/
將導致"a"b"
/".+?"/
將產生"a"
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.