HypeZ
HypeZ

Reputation: 4127

Replace in-string characters with regex in javascript

i'm pretty unconfident with regex and i need to do this simple work: i have an input string like this:

<a id="randomid">some text ( +1 even more text)</a>

now i need to replace that "1", i know it will always be between ( + and a space, how can i do this with regex?

That string is generated by ASP.NET inside a asp:HyperLink component, my first try was to generate that number inside a <span> with know id, but looks like asp.net remove all my html tags inside a ASP component

Upvotes: 0

Views: 221

Answers (2)

vdua
vdua

Reputation: 1331

If your assumption is correct, this will also work for you, it will replace the first occurance of "( +number" with "( +replaceNumber".

var regex = /\(\s+\+[0-9]+/
var replaceNumber = 2;
$('a#randomid').text().replace(regex, "( +"+replaceNumber);

TO replace all the occurances change the regex to

var regex = /\(\s+\+[0-9]+/g

Upvotes: 1

michael
michael

Reputation: 4483

Assuming you're using jQuery...

$('a#randomid').text().replace(/(.+ \( \+)([0-9]+)(.+)/, "$12$3")

Will give you...

some text ( +2 even more text)

Upvotes: 0

Related Questions