Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace string regex

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

like image 887
user602865 Avatar asked Mar 02 '12 17:03

user602865


People also ask

Does string replace take regex?

The Regex. Replace(String, MatchEvaluator, Int32, Int32) method is useful for replacing a regular expression match if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. For more information about numbered capturing groups, see Grouping Constructs.

What is replace () in JavaScript?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.


3 Answers

Does this fulfill your needs?

mystring.replace(/\[code:([0-9]+)\]/g, '<a href="someurl/$1">somelink</a>');
like image 196
Another Code Avatar answered Oct 16 '22 09:10

Another Code


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)
​
like image 31
qwertymk Avatar answered Oct 16 '22 08:10

qwertymk


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'

like image 1
Linus Thiel Avatar answered Oct 16 '22 09:10

Linus Thiel