简体   繁体   中英

Getting syntax error while RegEx check

This is the first time I am using RegEx in NodeJS.

AIM : very basic check on URL, if it's valid or not. I found this regex . Below is my code,

var URL = "https://www.google.com/";
var regEx = "^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
if(URL.match(regEx)) {
   console.log('matches');
} else {
   console.log('doesnt match');
}

Now, I am getting some syntax error, and I can't find the solution. Error is like, "Range out of order in character class". I have no idea about character class or RegEx. Please, someone help :) .

This is because you are providing your regex as String

Try following

var URL = "https://www.google.com/";
var regEx = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/;

if(URL.match(regEx)) {
    console.log('matches');
} else {
    console.log('doesnt match');
}

You can read https://www.w3schools.com/jsref/jsref_obj_regexp.asp for more details on regex in javascript.

var t = /^foo(bar)?$/i;
alert(t instanceof RegExp);//returns true

Keep in mind that as Regex is not a primitive data type but its a objext of RegExp ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp )

Change the code as bellow

var URL = "https://www.google.com/";
var regEx = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\ 
(\)\*\+,;=.]+$/;
if(URL.match(regEx)) {
   console.log('matches');
 } else {
   console.log('doesnt match');
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM