tarzanbappa
tarzanbappa

Reputation: 4958

Regex Javascript Match string by first two characters

I have to match a string by it's first two letters using Regex to check a specific two characters available as the first two letters of a string. Here assume that the first two characters are 'XX'.

And the strings I need to match are

So I need to filter this list to get strings that only starts with 'XX'

code I tried so far

var filteredArr = [];
var arr = [ "ABCDS ", "XXDER ", "DERHJ ", "XXUIO" ];
var re = new RegExp('^[a-zA-Z]{2}');
jQuery.each( arr, function( i, val ) {

if(re.test(val )){
  filteredArr.push(val);
}
});

What will be the exact Regex pattern to check the string that starts with 'XX'

Upvotes: 2

Views: 6976

Answers (6)

maioman
maioman

Reputation: 18744

I suggest string match :

var arr = [ "ABCDS ", "XXDER ", "DERHJ ", "XXUIO" ];

var r = arr.filter(x => x.match(/^XX/))

console.log(r)

Upvotes: 0

Munawir
Munawir

Reputation: 3356

You can simply use JavaScript .startsWith() method.

var arr = [ "ABCDS ", "XXDER ", "DERHJ ", "XXUIO" ];

var filteredArr = arr.filter(function(val){
  return val.startsWith("XX");
});

console.log(filteredArr);

Upvotes: 4

Atal Kishore
Atal Kishore

Reputation: 4738

 var filteredArr = [];
 var arr = [ "ABCDS ", "XXDER ", "DERHJ ", "XXUIO" ];
 var re = new RegExp('^XX');
 jQuery.each( arr, function( i, val ) {

 if(re.test(val )){
 filteredArr.push(val);
 }
});
  • ^ means match at the beginning of the line

Upvotes: 1

Andy
Andy

Reputation: 63524

Use filter with a less-complex regex:

var filtered = arr.filter(function (el) {
  return /^X{2}/.test(el);
});

DEMO

Upvotes: 0

jcubic
jcubic

Reputation: 66518

Try this:

var arr = [ "ABCDS ", "XXDER ", "DERHJ ", "XXUIO" ];
// match if two letters at the beginning are the same
var re = new RegExp('^([a-zA-Z])\\1');
var filteredArr = arr.filter(function(val) {
  return re.test(val);
});
document.body.innerHTML = JSON.stringify(filteredArr);

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68393

simply try

var filteredMatches = arr.filter(function(val){
  return val.indexOf("XX") == 0;
});

Upvotes: 7

Related Questions