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
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.
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.
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.
Does this fulfill your needs?
mystring.replace(/\[code:([0-9]+)\]/g, '<a href="someurl/$1">somelink</a>');
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)
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With