简体   繁体   中英

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

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

Assuming you're using jQuery...

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

Will give you...

some text ( +2 even more text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM