-1

I have a case wherein I want to search for all Hello (World) in an array. Hello (World) is coming from a variable and can change. I want to achieve this using RegExp and not indexOf or includes methods.

testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)']

My match should return index 1 & 2 as answers.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Gautam
  • 815
  • 6
  • 15

3 Answers3

1

Use the RegExp constructor after escaping the string (algorithm from this answer), and use some array methods:

const testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)'];
const string = "Hello (World)".replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const regex = new RegExp(string, "i");
const indexes = testArray.map((e, i) => e.match(regex) == null ? null : i).filter(e => e != null);
console.log(indexes);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
-1

This expression might help you to do so:

(\w+)\s\((\w+)

You may not need to bound it from left and right, since your input strings are well structured. You might just focus on your desired capturing groups, which I have assumed, each one is a single word, which you can simply modify that.

With a simple string replace you can match and capture both of them.

enter image description here

RegEx Descriptive Graph

This graph shows how the expression would work and you can visualize other expressions in this link:

enter image description here

Performance Test

This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.

repeat = 1000000;
start = Date.now();

for (var i = repeat; i >= 0; i--) {
 var string = "Hello (World";
 var regex = /(\w+)\s\((\w+)/g;
 var match = string.replace(regex, "$1 & $2");
}

end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match  ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test.  ");
Emma
  • 27,428
  • 11
  • 44
  • 69
  • sorry I forgot to mention, `Hello (World)` is coming from a variable and can change – Gautam May 07 '19 at 05:18
  • 2
    None of this even attempts to answer the question. But nice emojis, I guess? – melpomene May 07 '19 at 05:20
  • Just because you misunderstood the question doesn't mean you can just edit OP's question to make your answer fit. Edit your answer so it applies to OP's question, not the other way round. – melpomene May 07 '19 at 05:41
-2

testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)'];
let indexes = [];
testArray.map((word,i)=>{
  if(word.match(/\(.*\)/)){
    indexes.push(i);
  }
});
console.log(indexes);
Shiva
  • 476
  • 3
  • 15