首页 > 解决方案 > 在 JavaScript 中为字符串中所有出现的单词添加前缀和后缀

问题描述

我有一个文本文件,我可以将其作为字符串读取,例如这样的......

你好这是一个测试字符串这是一个测试这只是一个测试好吗?我们能解决这个问题吗?Idk,也许这是不可能的。

我希望输出将“Foo”附加到前面,将“Bar”附加到每个“this”单词的后面(不区分大小写),以便输出如下所示:

你好 FooThisBar 是一个测试字符串 FoothisBar 是一个测试 FooTHISBar 只是一个测试好吗?我们能解决 FooThisBar 吗?Idk,也许是FoothiSBar,是不可能的。

标签: javascript

解决方案


正则表达式

匹配每一次出现"this"

简单replace捕获组

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)

仅当它是一个单词时才匹配"this"(与标点符号一起使用)

To avoid matching "this" inside a word (e.g, "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. E.g, 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 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)

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.


推荐阅读