![](/img/trans.png)
[英]How to target a dash or hyphen in RegEx if used in a javascript .replace?
[英]How to target a letter after a dash in Javascript replace using RegEx?
我這里有一個腳本,它通過按鈕的 onclick 更改文本區域中的值。 我使用 Javascript 替換與 RegEx 一起執行此操作。 所以每個數字都有一個指定的值。
然而,在這個示例中,我無法在匆忙上班后寫信。
const mapper = new Map(); mapper.set("10th", "11th"); mapper.set("-", "Deleted"); mapper.set("63-51", "40"); mapper.set("121AA", "95"); mapper.set("121-I", "Deleted"); mapper.set("121-OO", "Deleted"); function fixtext() { const elm = document.getElementById("textarea1"); if (elm) { elm.value = elm.value.replace( /\b\d+(?:[AZ]|([AZ])\1|d|th|st|nd)?(|\-\d+)?\b/g, m => mapper.has(m)? mapper.get(m): m ); } }
<textarea id="textarea1" rows="4" cols="50">121AA will become 95 and 63-51 will become 40. This should be the same for 121-I and 121-OO.</textarea> <button class="nbtngreen" onclick="fixtext()">Update</button>
因此,單擊按鈕后, 121-I
應按指定變為Deleted
。 121-OO
也是如此。
對於如何修復我正在使用的 RegEx,我將不勝感激。 提前謝謝了!
您的正則表達式僅在-
之后匹配\d+
。 將其更改為[AZ\d]+
以匹配那里的字母或數字。
您不需要在帶有?
的組內使用空字符串的替代方法量詞,因為量詞意味着其他模式是可選的。
[AZ]|([AZ])\1
可以簡化為([AZ])\1?
.
const mapper = new Map(); mapper.set("10th", "11th"); mapper.set("-", "Deleted"); mapper.set("63-51", "40"); mapper.set("121AA", "95"); mapper.set("121-I", "Deleted"); mapper.set("121-OO", "Deleted"); function fixtext() { const elm = document.getElementById("textarea1"); if (elm) { elm.value = elm.value.replace( /\b\d+(?:([AZ])\1?|d|th|st|nd)?(-[AZ\d]+)?\b/g, m => mapper.has(m)? mapper.get(m): m ); } }
<textarea id="textarea1" rows="4" cols="50">121AA will become 95 and 63-51 will become 40. This should be the same for 121-I and 121-OO.</textarea> <button class="nbtngreen" onclick="fixtext()">Update</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.