5

I have following string

hello[code:1], world [code:2], hello world

I want to replace this string to

hello <a href="someurl/1">someothercode</a>, world <a href="someurl/2">someothercode</a>, hello world

I want this String conversion using javascript reg ex

I tried

/\[code:(\d+)\]/

reg ex but not sure how to tokenize them

1
  • 2
    What is your question? What have you tried? Commented Mar 2, 2012 at 17:44

3 Answers 3

18

Does this fulfill your needs?

mystring.replace(/\[code:([0-9]+)\]/g, '<a href="someurl/$1">somelink</a>');
Sign up to request clarification or add additional context in comments.

Comments

5

DEMO

var s = 'hello[code:1], world [code:2], hello world';

var codes = {
    1: '<a href="someurl/1">someothercode</a>',
    2: '<a href="someurl/2">someothercode</a>'
};

s = s.replace(/\[code:(\d*)\]/g, function(a, b) {
    return codes[b]
})

document.write(s)
​

Comments

1

You're not completely clear on what you want, but this outputs your desired result:

"hello[code:1], world [code:2], hello world"
    .replace(/\[(.*?):(.*?)\]/g, '<a href="someurl/$2">someother$1</a>')

Output:

'hello<a href="someurl/1">someothercode</a>, world <a href="someurl/2">someothercode</a>, hello world'

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.