-1

Below I am trying to use regex to get the occurrence of certain strings.

  var value = "ab-2123 AB-332";
  // "i" is for case insensitive
  var regExp = new RegExp("(ab)[-][0-9]*", "gi"); 
  var searchedString = regExp.exec(value);
  console.log(searchedString); 

This only detects ab-2124 but not AB-33. Could some one please help me to figure out the mistake?

Kiren S
  • 2,939
  • 5
  • 40
  • 68
kada
  • 2,083
  • 4
  • 28
  • 53

2 Answers2

1

Use the match property instead of exec:

var value = "ab-2123 AB-332";
var re = new RegExp("(ab)[-][0-9]*", "gi");
var searchedString = value.match(re);
console.log(searchedString); 
Toto
  • 86,179
  • 61
  • 85
  • 118
0

Firstly, a few important typos corrected

var searchedString regExp.exec(value) should be var searchedString = regExp.exec(value)

console.log(searched string); should be console.log(searchedString);


regExp.exec() will only return your first match. If you want multiple, you could use String.match(regExp)

let value = "ab-2123 AB-332";

  let regExp = new RegExp("(ab)[-][0-9]*", "gi"); // "i" is for case insensitive
  let searchedString = value.match(regExp);
  console.log(searchedString);
Shiny
  • 4,735
  • 3
  • 15
  • 32