JavaScript / jQuery字符串替换为正则表达式
假设我使用jQuery检索的值。 然后我如何使用JavaScript / jQuery替换值的一部分。 例如:
字符串: "Hey I'm $$zach$$"
用Zach
替换$$zach$$
并保持其余的字符串完好无损?
使用正则表达式替换:
yourTextArea.value = yourTextArea.value.replace(/\$\$(.+?)\$\$/, '$1')
正则表达式的解释:
\$\$ two dollar signs ( start a group to capture . a character + one or more ? lazy capturing ) end the group \$\$ two more dollar signs
然后在字符串'$1'
使用捕获组。 $1
是指正则表达式捕获的组。
用这个:
str.replace(/\${2}(.*?)\${2}/g, "$1");
\${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, "$1");
标记:
的jsfiddle
将其包装在一个function中以便最佳使用:
var italics = function (str) { return str.replace(/\$\$(.*?)\$\$/g, "$1"); } italics($("#txt").val());
好像你想要制作类似于Markdown的语法。 为什么不在你的领域使用Markdown解析器而不是重新发明轮子呢?
Showdown JS正在积极开发中,您可以获得与任何其他markdown语法相同的Markdown语法。
使用字符串.replace
方法可以。
.replace(/\$\$(.*?)\$\$/g, '$1')
使用此选项,更改链接和标记以扩展linkifyfunction:
String.prototype.linkify = function() { var wikipediaPattern = /(.+?)<\/wikipedia>/g; return this.replace(wikipediaPattern, '$1'); }