简体   繁体   中英

javascript regexp “subword” replace

I have a phrase like

"everything is changing around me, wonderfull thing+, tthingxx"

and I want to modify every word that contains ***thing at the end of that word, or at most another character after "thing", like "+" or "h" or "x"...

something like

string = 'everything is changing around me, wonderful thing+, tthingxx'
regex = new RegExp('thing(\\+|[g-z])$','g');
string = string.replace(regex, '<b>thing$1</b>');

what I want? every is changing around me, wonderful , tthingxx 是我身边的变化,美妙

The result of my regexp? anything working... if I remove the $ all the words containing "thing" and at least another character after it are matched:

everything is changing around me, wonderful , t x X

I tryed everything but - in first place I can't understand very well technical english - and second I did't find the answer around.

what I have to do??? thanks in advance


the solution I found was using this regular expression

/thing([+g-z]){0,1}\b/g

or with the RegExp (I need it because I have to pass a variable):

myvar = 'thing';
regex = new RegExp(myvar + "([+g-z]){0,1}\\b" , "g");

I was missing the escape \\ when doing the regular expression in the second mode. But this isn't enough: the + goes out of the < b > and I don't really know why!!!


the solution that works as I want is the one by @Qtax:

/thing([+g-z])?(?!\w)/g

thank to the community!

在正则表达式中使用边界

\b\w+thing(\+|[g-z])?\b

If I understand what you want, then:

string = 'everything is changing around me, wonderful thing+, tthingxx';
string = string.replace(/thing(\b|[+g-z]$)/g, '<b>thing$1</b>');

...which results in:

every<b>thing</b> is changing around me, wonderful <b>thing</b>+, tthingxx

\\b is a word boundary, so what the regular expression says is anywhere it finds "thing" followed by a word boundary or + or gz at the end of the string, do the replacement.

要解决使用\\b+不匹配的问题,可以使用(?!\\w)代替\\b ,例如:

thing[+g-z]?(?!\w)

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