JavaScript / jQuery字符串替换为正则表达式 [英] JavaScript/jQuery String Replace With Regex

查看:235
本文介绍了JavaScript / jQuery字符串替换为正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我使用jQuery检索< textarea> 的值。然后我如何使用JavaScript / jQuery替换值的一部分。例如:

Let's say I retrieve the value of a <textarea> using jQuery. How can I then replace a portion of the value using JavaScript/jQuery. For example:

string:嘿,我是$$ zach $$

使用< i> Zach< / i> $$ zach $$ >

replace $$zach$$ with <i>Zach</i>

仍然保持字符串的其余部分完好无损?

And still keep the rest of the string intact?

推荐答案

使用正则表达式替换:

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 指的是正则表达式捕获的组。

The capture group is then used in the string '<i>$1</i>'. $1 refers to the group that the regex has captured.

这篇关于JavaScript / jQuery字符串替换为正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆