简体   繁体   中英

How to add white space in regular expression in Javascript

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.

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.

Try this on

^\{\{[a-z]*\s[a-z]*\}\}$

Explanation:

  • \\{ - Matches a literal { symbol.

  • \\{ - Matches a literal { symbol.

  • [az]* - 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 *.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM