Dinesh
Dinesh

Reputation: 51

Split string and get array using regExp in javascript/node js

I am writing js code to get array of elements after splitting using regular expression.

 var data = "ABCXYZ88";
 var regexp = "([A-Z]{3})([A-Z]{3}d{2})";
 console.log(data.split(regexp));

It returns [ 'ABCXYZ88' ]

But I am expecting something like ['ABC','XYZ','88']

Any thoughts?

Upvotes: 1

Views: 2938

Answers (3)

Jérémie L
Jérémie L

Reputation: 775

  1. Your regexp is not a RegExp object but a string.
  2. Your capturing groups are not correct.
  3. String.prototype.split() is not the function you need. What split() does:
var myString = 'Hello World. How are you doing?';
var splits = myString.split(' ', 3);

console.log(splits); // ["Hello", "World.", "How"]

What you need:

var data = 'ABCXYZ88';
var regexp = /^([A-Z]{3})([A-Z]{3})(\d{2})$/;
var match = data.match(regexp);
console.log(match.slice(1)); // ["ABC", "XYZ", "88"]

Upvotes: 1

Mike Chamberlain
Mike Chamberlain

Reputation: 42440

I fixed your regex, then matched it against your string and extracted the relevant capturing groups:

var regex = /([A-Z]{3})([A-Z]{3})(\d{2})/g;
var str = 'ABCXYZ88';
let m = regex.exec(str);
if (m !== null) {
   console.log(m.slice(1)); // prints ["ABC", "XYZ", "88"]
}

In your case, I don't think you can split using a regex as you were trying, as there don't seem to be any delimiting characters to match against. For this to work, you'd have to have a string like 'ABC|XYZ|88'; then you could do 'ABC|XYZ|88'.split(/\|/g). (Of course, you wouldn't use a regex for such a simple case.)

Upvotes: 1

Muhammad Sajjad
Muhammad Sajjad

Reputation: 18

Try this. I hope this is what you are looking for.

      var reg = data.match(/^([A-Z]{3})([A-Z]{3})(\d{2})$/).slice(1);

https://jsfiddle.net/m5pgpkje/1/

Upvotes: 0

Related Questions