1

I need to replace [link]0[/link] with <a href=...

Now, the links are saved in an array links and the number inside [link][/link] is the pointer to links index.

I am trying to do next:

txt.replace( /\[link\](\d+)\[\/link\]/ , "<a href='" + links[ THE_INDEX ][ 0 ] + "' target='_blank'>" + ( links[ THE_INDEX ][ 1 ] || links[ THE_INDEX ][ 0 ] ) + "</a>" );

but I don't know, how to pass the saved value. Could you help me solve it?

P.S. I know I could make loop and use the exec() to save value and pass it, but I want to know, is it possible to do it like I sayd above.

For a more simple example of expectation

my_array = [ "data1", "data2", "data3" ];

"xxx1xxx".replace( /xxx(\d+)xxx/, "my_data=" + my_array[ THE_MATCH ] ); // should be "my_data=data1"
"xxx3xxx".replace( /xxx(\d+)xxx/, "my_data=" + my_array[ THE_MATCH ] ); // should be "my_data=data3"

Where THE_MATCH is taken from the regex match.

1
  • 1
    just edited your question to try to remove noise from the example. If you don't like don't hesitate to turn it back. Commented May 14, 2012 at 14:11

1 Answer 1

1

Found the solution:

function replacer(str, p1, p2 ){
    return "<a href='" + links[ p1 ] + "'></a>"
}
var newString = "XXzzzz".replace(/(X*)(z*)/, replacer)

While the values passed to replacer() as p1, p2 are the matched values. The amount of p arguments in replacer() needs to be as the amount of matched values.

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

1 Comment

Yes.. I was just to say the same: stackoverflow.com/questions/7192436/… (duplicated? :))

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.