Javascript replace string regex

29.6k views Asked by At

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

3

There are 3 answers

0
Another Code On BEST ANSWER

Does this fulfill your needs?

mystring.replace(/\[code:([0-9]+)\]/g, '<a href="someurl/$1">somelink</a>');
0
Linus Thiel On

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'

0
qwertymk On

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)
​