[英]Capture words between two special characters
I have a string like this: 我有一个像这样的字符串:
"some string, some $special$ string, some string, some string, some $special$ string,..."
I need to capture all words between two $
notation and put words inside <code></code>
tag. 我需要捕获两个
$
表示法之间的所有单词,并将单词放在<code></code>
标记内。 The result of above string should be this: 以上字符串的结果应为:
"some string, some <code>special</code> string, some string, some string, some <code>special</code> string,..."
How can I do this via javascript or jquery? 如何通过javascript或jquery做到这一点?
您可以使用替换功能和简单的正则表达式:
'your text ...'.replace(/\$(.+?)\$/g, '<code>$1</code>')
Use regex
in replace
as follow: 在
replace
使用regex
,如下所示:
var myStr = "some string, some $special$ string, some string, some string, some $NotSospecial$ string,...";
myStr = myStr.replace(/\$(\w+)\$/g, '<code>$1</code>');
\\$
: This will escape $
for exact match \\$
:这将使$
完全匹配 (\\w+)
: Capturing group: will match any characters any no. (\\w+)
:捕获组:将匹配任何字符。 of time g
: Global match. g
:全局匹配。 to continue even after first match $1
: The match from capturing group $1
:捕获组的匹配 Demo: https://jsfiddle.net/tusharj/o5yn5ast/ 演示: https : //jsfiddle.net/tusharj/o5yn5ast/
Using regex, and an overload of string.replace
which takes a regular expression and a replacer function: 使用正则表达式,以及
string.replace
的重载,它需要一个正则表达式和一个replacer函数:
var re = /\\$(.*?)\\$/g; var input = "some string, some $special$ string, some string, some string, some $special$ string,..."; var result = input.replace(re,function(match,g1){ return "<code>" + g1 + "</code>"; }); alert(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.