javascript - 在 JavaScript 中为字符串中所有出现的单词添加前缀和后缀
问题描述
我有一个文本文件,我可以将其作为字符串读取,例如这样的......
你好这是一个测试字符串这是一个测试这只是一个测试好吗?我们能解决这个问题吗?Idk,也许这是不可能的。
我希望输出将“Foo”附加到前面,将“Bar”附加到每个“this”单词的后面(不区分大小写),以便输出如下所示:
你好 FooThisBar 是一个测试字符串 FoothisBar 是一个测试 FooTHISBar 只是一个测试好吗?我们能解决 FooThisBar 吗?Idk,也许是FoothiSBar,是不可能的。
解决方案
正则表达式
匹配每一次出现"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.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 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.
推荐阅读
- r - 为双变量生存审查数据编写语法以拟合 R 中的 copula 模型
- javascript - 使用 p5js 创建多个可点击的 div
- java - Java-FX 非控制器类文件
- javascript - 在局部视图中访问表
- ruby-on-rails - 根或嵌套对象中的 Rails 强参数
- javascript - 基于电子表格值的 Google 表单中的表单验证
- python - 如何使用用户输入和打印更新的列表来减少列表中的值
- python - pandas.DataFrame.drop_duplicates(inplace=True) 抛出 'TypeError: unhashable type: 'dict''
- r - ggplot2::geom_text() 的奇怪行为
- android - 如果 Prev Data 与 Listview 中的当前数据相同,则隐藏 textview