22

First of all, here is my code snippet:

var str = '<!--:de-->some german text<!--:--><!--:en-->some english text<!--:-->';
var match =  str.match(/de-->([^<]+).+?en[^>]+>([^<]+)/i);
var textInDe = match[1]; 
var textInEn = match[2];

I've got this regex validation (thanks to The Mask) which works great.

Now, I want to check with an if-statement if this regex applies to some string or not. I'm using Javascript jquery.

Thanks in advance :)

3 Answers 3

60

You can use RegExp.test

if(/de-->([^<]+).+?en[^>]+>([^<]+)/i.test(str)) {
   // something
}
Sign up to request clarification or add additional context in comments.

2 Comments

hm i dont really know how it should work?! how it would looks like in an if statement? if(…== true) or what?
@YeppThat'sMe You don't need to have == true in an if statement, literally ever. Maybe === true, but definitely not the other
4
var str = '<!--:de-->some german text<!--:--><!--:en-->some english text<!--:-->';
var match =  str.match(/de-->([^<]+).+?en[^>]+>([^<]+)/i);
if(match.length > 0){
//successful match
}

OR

var re = new RegExp('regex string');
  if (somestring.match(re)) {
//successful match
}

1 Comment

If there are no matches then match is null meaning you can't do match.length. If you change the if statement if (match){... then it will work.
3

How about this?

function IsMatch(v) {
   //basically build your regex here
   var exp = new RegExp("^de-->([^<]+).+?en[^>]+>([^<]+)$"); return exp.test(v);
}

To call it:
if(IsMatch('Your string')) alert('Found'); else alert('Not Found');

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.