0

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]',..... ]
Nabeel
  • 784
  • 3
  • 9
  • 23

3 Answers3

2

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);
Kevin
  • 1,068
  • 5
  • 14
  • 16
  • thnx it worked. What if `Hello[0] hello[2] hell Welcome hello[2]` i want to get the unique occurrence of `hello[2]` ? – Nabeel Jan 06 '23 at 15:23
  • @Nabeel easiest way would be to add some JavaScript magic, like: https://stackoverflow.com/a/14438954/3653544 or https://stackoverflow.com/a/42123984/3653544 – Kevin Jan 06 '23 at 15:27
1

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);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

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