假设我检索了 <textarea>
的值使用 jQuery。然后我如何使用 JavaScript/jQuery 替换该值的一部分。例如:
字符串:"Hey I'm $$zach$$"
替换$$zach$$
与 <i>Zach</i>
并且仍然保持字符串的其余部分完好无损?
最佳答案
使用正则表达式替换:
yourTextArea.value = yourTextArea.value.replace(/\$\$(.+?)\$\$/, '<i>$1</i>')
正则表达式的解释:
\$\$ two dollar signs
( start a group to capture
. a character
+ one or more
? lazy capturing
) end the group
\$\$ two more dollar signs
然后在字符串 '<i>$1</i>'
中使用捕获组。 $1
指正则表达式已捕获的组。
关于JavaScript/jQuery 字符串替换为正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16137562/