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

Zac*_*ach 22 javascript regex jquery

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

串: "Hey I'm $$zach$$"

替换$$zach$$<i>Zach</i>

并保持其余的字符串完好无损?

Doo*_*nob 43

使用正则表达式替换:

yourTextArea.value = yourTextArea.value.replace(/\$\$(.+?)\$\$/, '<i>$1</i>')
Run Code Online (Sandbox Code Playgroud)

正则表达式的解释:

\$\$  two dollar signs
(     start a group to capture
.     a character
+     one or more
?     lazy capturing
)     end the group
\$\$  two more dollar signs
Run Code Online (Sandbox Code Playgroud)

然后在字符串中使用捕获组'<i>$1</i>'.$1是指正则表达式捕获的组.


Som*_*ica 12

用这个:

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

的jsfiddle

如果你想在jQuery中有所作为:

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

标记:

<textarea id="txt">I'm $$Zach$$</textarea>
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

将其包装在一个功能中以便最佳使用:

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

italics($("#txt").val());
Run Code Online (Sandbox Code Playgroud)

好像你想要制作类似于Markdown的语法.为什么不在你的领域使用Markdown解析器而不是重新发明轮子呢?

Showdown JS正在积极开发中,您可以获得与任何其他markdown语法相同的Markdown语法.