繁体   English   中英

在 JavaScript 中为字符串中所有出现的单词添加前缀和后缀

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

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

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

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

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

正则表达式

匹配"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" (使用标点符号)

为避免在单词内匹配"this" (例如, "abcthisdef" ),您可以使用否定前瞻和否定后视

 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)

非正则表达式

您可以用空格分割字符串,映射到结果数组并仅当项目(转换为小写时)等于"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)

上述解决方案的警告是,当它在标点符号旁边时,它不会匹配"this" 例如,它不会匹配"this." .

要也用尾随标点符号替换单词,您可以首先使用匹配非字母数字单词的正则表达式拆分字符串,检查第一项是否为"this" ,然后在之后连接第二项(在第一次join之后,因为第二项在解构赋值中是一个尾随标点字符数组):

 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)

请注意,如果出现之前有标点符号,则此解决方案将不起作用。 例如,它会将"this"转换为this" 。为避免这种情况,请使用上面推荐的正则表达式解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM