简体   繁体   中英

replace a word in text with javascript but not if the word is in a bigger word.

Hi I want to replace words in a text string, but this seems harder than I thought. It should be in javascript. Say my word is 'ion'. It should replace when I see in the text: my ion, "ion", ion: is cool, (ion), [ion]. But not when it is part of another word like position (positION).

Probably it should be done with regular expressions but I don't know how.

Try /(\\bion\\b)/gi

\b    assert position at a word boundary
i     modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
g     modifier: global. All matches (don't return on first match)

parenthesis is used to group the match that can be retried from index 1.

Here is demo on regex101


Sample code: ( No need to group it if you just want to replace it )

str.replace(/\bion\b/gi, "XYZ");

You may craft regexp which will tell something like: [not a letter]ion[not a letter].

This would look like: [^a-zA-Z]ion[^a-zA-Z]

EDIT:

To keep surrounding characters you need to use placeholders. So the final solution will look like: str.replace(/([^a-zA-Z])ion([^a-zA-Z])/g, '$1REPLACED$2') REPLACED is obviously the word you would like replace with.

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