Regular expression to get all words inside specific patterns (% %)
11,279
Use String match with /%(\w+)%/g
regular expression
Explanation for /%(\w+)%/g
-
%
matches the character % literally -
1st Capturing group
(\w+)
-
\w+
match any word character [a-zA-Z0-9_]- Quantifier:
+
Between one and unlimited times, as many times as possible, giving back as needed[greedy]
- Quantifier:
-
-
%
matches the character % literally -
g modifier:
global. All matches (don't return on first match)
var string = 'this is a %varA% and %varB% and %varC%';
var regExp = /%(\w+)%/g;
document.write(string.match(regExp));
Related videos on Youtube
Author by
Gerry
Updated on September 14, 2022Comments
-
Gerry over 1 year
All I want is this:
The sentences will have some words within % % and I want to extract all of them.
For e.g.
"This is a %varA% and %varB% and that one is a %VarC%"
and when I run it through the Javascript exec I'd like to get %varA%, %varB%, and %varC% in an array.
What would the pattern be? I've tried a number of iterations and none of them gets me each word separately. VarA and VarB etc. will all be words with just a-Z and 0-9, no special characters.
-
anubhava over 7 years
/%(\w+)%/g
should work for you.
-