Home > Enterprise >  Find all matches in string
Find all matches in string

Time:01-07

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]',..... ]

CodePudding user response:

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);

CodePudding user response:

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);

CodePudding user response:

var str = 'Hello[0] hello[2] hell Welcome to JavaScript.';
var regex = /Hello\[[0-9] \] /gi ;
var result = str.match(regex)
console.log(result)

  • Related