Reputation: 794
I'm using the regex to search for all instances of the string that matches Hello[n] pattern.
var str = 'Hello[0] hello[2] hell Welcome to JavaScript.';
var regex = /hello+/gi;
var result = str.match(regex);
The code above produces the following outcome.
[ 'Hello', 'hello' ]
I want to know how to modify my regex to produce the following result.
[ 'Hello[0]', 'hello[1]',..... ]
Upvotes: 0
Views: 78
Reputation: 11
var str = 'Hello[0] hello[2] hell Welcome to JavaScript.';
var regex = /Hello\[[0-9]+\]+/gi ;
var result = str.match(regex)
console.log(result)
Upvotes: 1
Reputation: 522712
Extend your current regex pattern to include the square brackets:
var str = 'Hello[0] hello[2] hell Welcome to JavaScript.';
var matches = str.match(/hello\[.*?\]/gi);
console.log(matches);
Upvotes: 1
Reputation: 1130
If you want to include the number, you've to change the Regex to hello\[\d+\]+
.
Working example: https://regex101.com/r/Xtt6ds/1
So you get:
var str = 'Hello[0] hello[2] hell Welcome to JavaScript.';
var regex = /hello\[\d+\]+/gi;
var result = str.match(regex);
Upvotes: 2