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