Reputation: 4870
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.
Upvotes: 1
Views: 20751
Reputation: 1620
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 compulsory character then use + instead of *.
Upvotes: 1
Reputation: 174696
Give 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.
Upvotes: 2
Reputation: 41838
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 bracesUpvotes: 0