0

I have three string and i need to check if one of them contains the other 2 in the same order given, right now i am using alot of conditions to achive this, is there a way to simplify it using regex?

here is the code:

var a = '**';
var b = '##';
var phrase = '**Lorem ipsum dolor sit amet##';

if(phrase.includes(a) && phrase.includes(b) && (phrase.indexOf(a) < phrase.indexOf(b))) {
  // add logic
}
DAbuzied
  • 111
  • 2
  • 8

1 Answers1

2

You could use a pattern to match ** before ##

^(?:(?!##|\*\*).)*\*\*.*##
  • ^ Start of string
  • (?:(?!##|\*\*).)* Match any char while not directly followed by either ## or **
  • \*\* First match **
  • .* Match any character 0+ times
  • ## Match ##

Regex demo

var phrase = '**Lorem ipsum dolor sit amet##';

if (phrase.match(/^(?:(?!##|\*\*).)*\*\*.*##/)) {
  // add logic
}

var phrases = [
  '**Lorem ipsum dolor sit amet##',
  'test****#**##',
  '##**Lorem ipsum dolor sit amet##',
  '##**##**',
];
phrases.forEach(phrase => {
  if (phrase.match(/^(?:(?!##|\*\*).)*\*\*.*##/)) {
    console.log(`Match for ${phrase}`);
  } else {
    console.log(`No match for ${phrase}`);
  }
});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70