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

29
假设我使用jQuery获取了<textarea>的值,如何使用JavaScript/jQuery替换该值的一部分?例如:
字符串:"Hey I'm $$zach$$"$$zach$$替换为<i>Zach</i> 仍然保留其余的字符串不变?

我看到你在示例中使用了 &lt; 等符号。你想要使用 < 还是 &lt; - timss
4个回答

47

使用正则表达式替换:

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


如果举个例子,我想要替换“$$大家好$$”怎么办? - Zach
在斜杠后面不要忘记加上 'g'。 只有加上这个字母后,它才能正常工作。 - Victor Augusto

13

使用这个:

str.replace(/\${2}(.*?)\${2}/g, "<I>$1</I>");
\${2} matches two $ characters
(.*?) matches your string to be wrapped
\${2} same as above
/g matches globally

jsFiddle

如果你想使用jQuery实现这个功能:

$("#txt").val().replace(/\${2}(.*?)\${2}/g, "<I>$1</I>");

标记:

<textarea id="txt">I'm $$Zach$$</textarea>

jsFiddle

为了最佳使用效果,将其包装在函数中:

var italics = function (str) {
    return str.replace(/\$\$(.*?)\$\$/g, "<I>$1</I>");
}

italics($("#txt").val());

看起来你想要创建一个类似于Markdown的语法。为什么不直接在你的字段中使用Markdown解析器,而不是重复造轮子呢?

Showdown JS正在积极开发中,你可以得到与其他任何Markdown语法相同的Markdown语法。


3

使用以下代码,更改链接和标记以扩展linkify函数:

String.prototype.linkify = function() {
    var wikipediaPattern = /<wikipedia>(.+?)<\/wikipedia>/g; 
    return this.replace(wikipediaPattern, '<a href="http://fr.wikipedia.org/wiki/$1">$1</a>');
}

3
使用字符串的.replace方法即可。
.replace(/\$\$(.*?)\$\$/g, '<I>$1</I>')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接