0
 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.

2 Answers 2

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"

Sign up to request clarification or add additional context in comments.

1 Comment

Or better yet, instead of: .{1,80}? use: [^)]{1,80}
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.