Home > other >  is there a regex expression to replace this if condition
is there a regex expression to replace this if condition

Time:11-22

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
}

CodePudding user response:

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}`);
  }
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related