Skip to content Skip to sidebar Skip to footer

Regular Expression In String.replace With A Callback Function

function helpLinkConvert(str, p1, offset, s) { return ''+p1+''; } var message =

Solution 1:

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:

functionhelpLinkConvert(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"

Solution 2:

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.

Post a Comment for "Regular Expression In String.replace With A Callback Function"