简体   繁体   English

带有回调函数的string.replace中的正则表达式

[英]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);

This is what I want to do, 这就是我要做的

Before: 之前:

(look: this) is a (look: stackoverflow) question. (外观:这)是一个(外观:stackoverflow)问题。

After: 后:

this is a stackoverflow question 是一个stackoverflow问题


When there is only one matched string, it's working but in other cases It's not working properly, 当只有一个匹配的字符串时,它可以工作,但在其他情况下,它不能正常工作,

How can I do that? 我怎样才能做到这一点? Thanks. 谢谢。

You need to add the global g modifier , and a non-greedy match so the regular expression finds all matches: 您需要添加全局g修饰符和一个非贪心匹配项,以便正则表达式可以找到所有匹配项:

/\\(look: (.{1,80}?)\\)/g

In your code: 在您的代码中:

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);

Outputs: 输出:

"<a href="look.php?word=this">this</a> is a <a href="look.php?word=stackoverflow">stackoverflow</a> question"

Use the g flag: 使用g标志:

message .replace(/\(look: (.{1,80})\)/g, helpLinkConvert);

The g (stands for "global") will match against all occurrences of the pattern on this string, instead of just the first one. g (代表“全局”)将与该字符串上所有出现的模式匹配,而不仅仅是第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM