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

Time:10-11

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.

Thanks

CodePudding user response:

You can use String.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)

To ensure that we only replace this when it is a word (pointed out by madflow), you can split the string by a space and map to replace every occurrence of "this", then join back into a string:

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)

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 joining, 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)

CodePudding user response:

Using split and join

const phrase = "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 stripped = phrase.split(" ").map(e => e.toLowerCase() == "this" ? `Foo${e}Bar` : e).join(' ')
console.log(stripped)

  • Related