The RegExp quantifier plus (+) use to match the preceding (before) item 1 or more times in the given string. ie. /bo*/ matches with the book in this is book and ba in fruits in basket, but nothing in riding cycle.
1 const regex = new RegExp(/bo+/g);
2 const str = 'book in rack';
3
4 let res1 = regex.test(str);
5 console.log("String has char sequence 'bo' :", res1);
6
7 let res2 = str.match(regex);
8 console.log("All matches :", res2);
In the above example, a regex object is created by specifying a quantifier plus (+) and a string value. It is validated and match using methods which returns respective values and printed on console. It matches the string bo from the book and returns.
1 String has char sequence 'bo' : true
2 All matches : [ 'boo' ]
Note : x+? - The ? character after the quantifier makes the quantifier non-greedy, that means it will stop as soon as it finds a match.
Example 2
1 const regex = new RegExp(/b[oa]+/);
2
3 const str1 = 'fruits in basket';
4 const str2 = 'break keyword';
5
6
7 let res1 = regex.test(str1);
8 let res2 = regex.test(str2);
9
10 console.log('String includes sequence bo or ba :', res1);
11 console.log('String includes sequence bo or ba :', res2);
In the above example, a regex is define that validates whether letter b followed by letter o or a. A strings variables are define by assigning a string literals. A regex method test() called by passing a string that returns boolean value true, if string matches the regex, otherwise false.
1 String includes sequence bo or ba : true
2 String includes sequence bo or ba : false
Filter elements using plus quantifier
Filter elements using plus quantifier
1 const array = ['this', 'tenth', 'thooth', 'those', 'script', 'that']
2
3
4 const regex = new RegExp(/th[io]+/);
5
6
7 let res = array.filter(ele => regex.test(ele));
8 console.log("A resulting array : ", res);
In the above example, an array is define and initialized with string literals. A regex define that validates string includes character sequence th followed by i or o one or more time. An array method filter() called by passing a callback function.
A callback function validates each element using regex method test(), it returns boolean value true, if an element matches with regex, otherwise false. A filter() method returns an array that includes an elements which matches with regex.
1 A resulting array : [ 'this', 'thooth', 'those' ]
Related options for your search