javascript - regular expression in string.replace with a callback function - Stack Overflow

function helpLinkConvert(str, p1, offset, s){return "<a href="look.php?word="+enc

 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.

After:

this is a stackoverflow question


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.

 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.

After:

this is a stackoverflow question


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.

Share Improve this question asked Dec 10, 2011 at 19:31 Okan KocyigitOkan Kocyigit 13.5k18 gold badges72 silver badges131 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

/\(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:

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744607326a4583547.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信