用回调函数替换 string.replace 中的正则表达式 [英] regular expression in string.replace with a callback function

查看:34
本文介绍了用回调函数替换 string.replace 中的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 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)问题.

(look: this) is a (look: stackoverflow) question.

之后:

this 是一个 stackoverflow 问题

当只有一个匹配的字符串时,它可以工作,但在其他情况下它不能正常工作,

When there is only one matched string, it's working but in other cases It's not working properly,

我该怎么做?谢谢.

推荐答案

您需要添加全局 g 修饰符和非贪婪匹配,以便正则表达式找到所有匹配:

You need to add the global g modifier , and a non-greedy match so the regular expression finds all matches:

/\(看:(.{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> 是一个 <a href="look.php?word=stackoverflow">stackoverflow</a>; 问题"

这篇关于用回调函数替换 string.replace 中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆