Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript check if regex apply

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

like image 485
YeppThat'sMe Avatar asked Jun 17 '11 19:06

YeppThat'sMe


People also ask

What does .test do in JavaScript?

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false .

How do you know if a string matches a pattern?

To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.

How do you evaluate a regular expression in JavaScript?

The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false. Where str is the string to be searched. This is required field.

What does .match do in JavaScript?

match() is a built-in function in JavaScript; it is used to search a string, for a match, against a regular expression. If it returns an Array object the match is found, if no match is found a Null value is returned.


3 Answers

You can use RegExp.test

if(/de-->([^<]+).+?en[^>]+>([^<]+)/i.test(str)) {
   // something
}
like image 134
Dogbert Avatar answered Sep 22 '22 14:09

Dogbert


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
}
like image 35
Satyajit Avatar answered Sep 19 '22 14:09

Satyajit


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');
like image 39
kheya Avatar answered Sep 19 '22 14:09

kheya