2

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

  • ABCDS
  • XXDER
  • DERHJ
  • XXUIO

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'

4
  • Do you want to check if first 2 characters are the same? Commented May 17, 2016 at 10:12
  • I recommend you these tools to avoid headaches : regex101.com & txt2re.com Commented May 17, 2016 at 10:13
  • No.. I want to check strings that starts with 'XX' Commented May 17, 2016 at 10:13
  • 3
    In that case you don't even need regex, just use indexOf Commented May 17, 2016 at 10:14

6 Answers 6

7

simply try

var filteredMatches = arr.filter(function(val){
  return val.indexOf("XX") == 0;
});
Sign up to request clarification or add additional context in comments.

Comments

4

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);

Comments

2

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);

Comments

1
 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

Comments

0

Use filter with a less-complex regex:

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

DEMO

Comments

0

I suggest string match :

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

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

console.log(r)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.