JavaScript/jQuery 字符串替换为正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16137562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript/jQuery String Replace With Regex
提问by Zach
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:
假设我<textarea>
使用 jQuery检索 a 的值。然后如何使用 JavaScript/jQuery 替换部分值。例如:
string: "Hey I'm $$zach$$"
细绳: "Hey I'm $$zach$$"
replace $$zach$$
with <i>Zach</i>
替换$$zach$$
为<i>Zach</i>
And still keep the rest of the string intact?
仍然保持字符串的其余部分完好无损?
回答by Doorknob
Use a regex replace:
使用正则表达式替换:
yourTextArea.value = yourTextArea.value.replace(/$$(.+?)$$/, '<i></i>')
Explanation of the regex:
正则表达式的解释:
$$ two dollar signs
( start a group to capture
. a character
+ one or more
? lazy capturing
) end the group
$$ two more dollar signs
The capture group is then used in the string '<i>$1</i>'
. $1
refers to the group that the regex has captured.
然后在字符串中使用捕获组'<i>$1</i>'
。$1
指的是正则表达式捕获的组。
回答by SomeShinyObject
Use this:
用这个:
str.replace(/${2}(.*?)${2}/g, "<I></I>");
${2} matches two $ characters
(.*?) matches your string to be wrapped
${2} same as above
/g matches globally
If you wanted something in jQuery:
如果你想要一些 jQuery 的东西:
$("#txt").val().replace(/${2}(.*?)${2}/g, "<I></I>");
Markup:
标记:
<textarea id="txt">I'm $$Zach$$</textarea>
Wrap it in a function for best use:
将其包装在一个函数中以实现最佳使用:
var italics = function (str) {
return str.replace(/$$(.*?)$$/g, "<I></I>");
}
italics($("#txt").val());
Seems like you want to make a syntax similar to Markdown. Why not just use a Markdown parser for your fields instead of reinventing the wheel?
好像你想制作一个类似于 Markdown 的语法。为什么不对您的字段使用 Markdown 解析器而不是重新发明轮子?
Showdown JSis actively developed and you get the same Markdown syntax as with any other markdown syntax.
Showdown JS正在积极开发中,您将获得与任何其他 Markdown 语法相同的 Markdown 语法。
回答by Nicolas Vannier
Use this, change link and tag for extended linkify function :
使用这个,更改链接和标签以扩展链接功能:
String.prototype.linkify = function() {
var wikipediaPattern = /<wikipedia>(.+?)<\/wikipedia>/g;
return this.replace(wikipediaPattern, '<a href="http://fr.wikipedia.org/wiki/"></a>');
}
回答by Explosion Pills
Using the string .replace
method will do.
使用字符串.replace
方法就可以了。
.replace(/$$(.*?)$$/g, '<I></I>')