JavaScript/jQuery 字符串替换为正则表达式

标签 javascript jquery regex

假设我检索了 <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/

相关文章:

javascript - 单击时展开一个 div(具有悬停翻转效果)

php - 突出显示字符串中的多个单词

java - 使用编译和正则表达式获取字符串中的所有匹配项

javascript - 使用 AngularJS 前端向 Express API 提交表单

javascript - 无法在 InDesign CC 脚本中调用菜单项

javascript - 如何检查数组的哪些元素相对于位置匹配

javascript - 如何在 polymer 中使用 jQuery 动态更改数组?

javascript - 如何验证动态添加的输入字段

regex - 生成与某些输入集匹配的正则表达式是否是一个可解决的问题?

javascript - AngularJS 自定义指令 : how to update parent variable specified in ng-model?