admin管理员组文章数量:1320661
I have a string {{my name}}
and i want to add white space in regular expression
var str = "{{my name}}";
var patt1 = /\{{\w{1,}\}}/gi;
var result = str.match(patt1);
console.log(result);
But result in not match.
Any solution for this.
I have a string {{my name}}
and i want to add white space in regular expression
var str = "{{my name}}";
var patt1 = /\{{\w{1,}\}}/gi;
var result = str.match(patt1);
console.log(result);
But result in not match.
Any solution for this.
Share Improve this question edited Jun 24, 2014 at 7:01 Nitish Kumar asked Jun 24, 2014 at 6:59 Nitish KumarNitish Kumar 4,8703 gold badges21 silver badges38 bronze badges 4- Where do you want to add the white space? – zx81 Commented Jun 24, 2014 at 7:04
- using your pattern.. /{{\w{1,}\ \w{1,}}}/gi – webkit Commented Jun 24, 2014 at 7:17
- \s - will match exact one space – Naresh Ravlani Commented Jun 24, 2014 at 7:27
- Hey there, following up on this, did one of the answers solve it for you, or is the question still there? – zx81 Commented Jun 25, 2014 at 21:14
3 Answers
Reset to default 2Give the word character\w
and the space character\s
inside character class[]
,
> var patt1 = /\{\{[\w\s]+\}\}/gi;
undefined
> var result = str.match(patt1);
undefined
> console.log(result);
[ '{{my name}}' ]
The above regex is as same as /\{\{[\w\s]{1,}\}\}/gi
Explanation:
\{
- Matches a literal{
symbol.\{
- Matches a literal{
symbol.[\w\s]+
- word character and space character are given inside Character class. It matches one or more word or space character.\}
- Matches a literal}
symbol.\}
- Matches a literal}
symbol.
Try this on
^\{\{[a-z]*\s[a-z]*\}\}$
Explanation:
\{ - Matches a literal { symbol.
\{ - Matches a literal { symbol.
[a-z]* - will match zero or more characters
\s - will match exact one space
\} - Matches a literal } symbol.
\} - Matches a literal } symbol.
If you want pulsory character then use + instead of *.
To match this pattern, use this simple regex:
{{[^}]+}}
The demo shows you what the pattern matches and doesn't match.
In JS:
match = subject.match(/{{[^}]+}}/);
To do a replacement around the pattern, use this:
result = subject.replace(/{{[^}]+}}/g, "Something$0Something_else");
Explanation
{{
matches your two opening braces[^}]+
matches one or more chars that are not a closing brace}}
matches your two closing braces
本文标签: regexHow to add white space in regular expression in JavascriptStack Overflow
版权声明:本文标题:regex - How to add white space in regular expression in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742065499a2418809.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论