[英]regular expression in string.replace with a callback function
function helpLinkConvert(str, p1, offset, s) {
return "<a href=\"look.php?word="
+encodeURIComponent(p1)+"\">"+p1+"</a>";
}
var message = "(look: this) is a (look: stackoverflow) question";
message = message .replace(/\(look: (.{1,80})\)/, helpLinkConvert);
這就是我要做的
之前:
(外觀:這)是一個(外觀:stackoverflow)問題。
后:
這是一個stackoverflow問題
當只有一個匹配的字符串時,它可以工作,但在其他情況下,它不能正常工作,
我怎樣才能做到這一點? 謝謝。
您需要添加全局g
修飾符和一個非貪心匹配項,以便正則表達式可以找到所有匹配項:
/\\(look: (.{1,80}?)\\)/g
在您的代碼中:
function helpLinkConvert(str, p1, offset, s) {
return "<a href=\"look.php?word="+encodeURIComponent(p1)+"\">"+p1+"</a>";
}
var message = "(look: this) is a (look: stackoverflow) question";
message = message.replace(/\(look: (.{1,80}?)\)/g, helpLinkConvert);
輸出:
"<a href="look.php?word=this">this</a> is a <a href="look.php?word=stackoverflow">stackoverflow</a> question"
使用g
標志:
message .replace(/\(look: (.{1,80})\)/g, helpLinkConvert);
g
(代表“全局”)將與該字符串上所有出現的模式匹配,而不僅僅是第一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.