[英]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"
每個出現 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.