简体   繁体   中英

Add prefix and suffix to all occurrences of a word in a string in JavaScript

I have a text file which I can read as a string for example something like this...

Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible.

I want the output to append "Foo" to the front and "Bar" to the back of every "this" word (case insensitive) so that the output will look like this:

Hello FooThisBar is a test string FoothisBar is a test FooTHISBar is just a test ok? Can we solve FooThisBar? Idk, maybe FoothiSBar, is just impossible.

Regex

Match every occurence of "this"

Simple replace with a capturing group :

 const str = "Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible."; const result = str.replace(/(this)/gi, "Foo$1Bar") console.log(result)

Only match "this" when it is a word (works with punctuation)

To avoid matching "this" inside a word (eg, "abcthisdef" ), you can use a negative lookahead and negative lookbehind :

 const str = "Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible."; const result = str.replace(/(?<!\\w)(this)(?!\\w)/gi, "Foo$1Bar") console.log(result)

Non-regex

You can split the string by a space, map through the resulting array and return the modified string only when the item (when converted to lowercase) is equal to "this" :

 const str = "Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible."; const result = str.split(" ").map(e => e.toLowerCase() == "this" ? `Foo${e}Bar` : e).join(' ') console.log(result)

The caveat with the above solution is that it will not match "this" when it is beside punctuation. Eg, it will not match "this." .

To also replace words with trailing punctuation, you can first split the string with a regex that matches non-alphanumeric words, check whether the first item is "this" , then concatenate the second item after (after first join ing, since the second item in the destructure assignment is an array of trailing punctuation characters):

 const str = "Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible. this??? this!"; const result = str.split(" ").map(e => { let [word, ...punctuation] = e.split(/(?!\\w)/g) return word.toLowerCase() == "this" ? `Foo${word}Bar${punctuation.join('')}` : e }).join(' ') console.log(result)

Note that this solution will not work if there is punctuation before the occurence. For example, it will convert "this" to this" . To avoid this, use the recommended regex solution above.

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