How check format of regular expression in javascript [duplicate] - javascript

This question already has answers here:
How to check if the input string is a valid Regular expression?
(6 answers)
Closed 7 years ago.
I have a regular expression and I want to check this regular expression is valid or not(correct format).
I try to use this code as below to check but it run not good
var regExp = new RegExp();
regExp.compile("^[\d\-]{0,64}"); => check OK.
regExp.compile("[[\d\-]{0,64}"); => check Not Good.
How to check my regular expression is correct format or not?
Please help me handle this case.

Use try/catch to catch the error when creating the regexp.
Object.defineProperty(RegExp, 'compile', {
value: function (regexp) {
try {
new RegExp(regexp);
return "OK";
} catch(e) {
return "Not Good";
}
}
});
Some might object to adding methods to the RegExp object. In the above, I've adopted your proposed interface implementing this as RegExp.compile.

Related

JS URL regex, allow only urls and empty string [duplicate]

This question already has answers here:
Regular expression which matches a pattern, or is an empty string
(5 answers)
Closed 2 years ago.
I have the following regext:
var regex = /^(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g;
function test() {
alert(regex.test(document.getElementById("myinput").value));
}
I want to allow url or empty string. regex solution please
How do I allow empty in this case?
https://jsfiddle.net/6kptovwc/2/
Thanks
Add an alternation with empty string (I've simplified a bit your regex):
^((?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b[-a-zA-Z0-9#:%_\+.~#?&\/=]*|)$
or
^((?:https?:\/\/)?(?:www\.)?[-\w#:%.+~#=]{2,256}\.[a-z]{2,6}\b[-\w#:%+.~#?&\/=]*|)$
Demo & explanation
Just add OR(||) condition
function test() {
const elm = document.getElementById("myinput")
alert(elm.value === '' || regex.test(elm.value));
}
^$|pattern
var regex = /^$|(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g;

Transform a "Regex" string to actual Regex in Javascript [duplicate]

This question already has answers here:
Converting user input string to regular expression
(14 answers)
Closed 3 years ago.
I need to pass a regular expression in a validation function in my code that can only be set by an administrator in a back office platform as a string (e.g. '/^(?:\d{8}|\d{11})$/'). After it is passed I need to take this string and transform it into an actual javascript regex in order to use it.
const validator = (regex, value) => {
if (value && regex.test(value)) {
return 'Yeah!!';
}
return null;
};
So I need this '/^(?:\d{8}|\d{11})$/' to be like this /^(?:\d{8}|\d{11})$/.
You can initialize a regex with the RegExp method (documentation on MDN):
The RegExp constructor creates a regular expression object for matching text with a pattern.
const regex2 = new RegExp('^(?:\\d{8}|\\d{11})$');
console.log(regex2); // /^(?:\d{8}|\d{11})$/
You could instantiate the RegExp class and use it in two ways:
First:
new RegExp('<expression>').test(...)
Second:
/<expression>/.test(...)
Both ways will create an RegExp instance.
When to use one over the other?
Using the new RegExp way you can pass variables to the expression, like that:
new RegExp('^abc' + myVar + '123$');
Which you can't do using the second way.

What's wrong with my regular expression for IP addresses? [duplicate]

This question already has answers here:
Javascript RegEx Not Working [duplicate]
(1 answer)
Why do regex constructors need to be double escaped?
(5 answers)
Closed 5 years ago.
I'm trying to check strings to see it they are a valid IP address:
export function checkIpIsValid(ip) {
const regex = new RegExp("^([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}$")
return regex.test(ip);
}
But this test is failing because it return true:
expect(checkIpIsValid("1.1.1.1")).toBe(true);
expect(checkIpIsValid("152.154.22.35")).toBe(true);
expect(checkIpIsValid("552.154.22.35")).toBe(false);
// These three are fine
// But the one below is not, it doesn't contain 4 parts so it should return false. Instead, it is returning true.
expect(checkIpIsValid("154.22.35")).toBe(false);
// Expected value to be (using ===):
// false
// Received:
// true
The thing is, when I check it on https://regex101.com/ it works fine on that case...
Don't use new RegExp(). This expects a string input, but your expression is not escaped for string. You just enclosed it in double quotes, that doesn't work.
Either use a regex literal:
function checkIpIsValid(ip) {
const regex = /^([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}$/;
return regex.test(ip);
}
or escape he expression properly:
function checkIpIsValid(ip) {
const regex = new RegExp("^([1-2]?[0-9]{1,2}\\.){3}[1-2]?[0-9]{1,2}$");
return regex.test(ip);
}
JS has regex literals exactly because that avoids the need for double-escaping. Use new RegExp() only for dynamically built expressions, not for fixed ones.
function checkIpIsValid(ip) {
return /^(?:\d{1,3}\.){3}\d{1,3}$/.test(ip);
}
checkIpIsValid('123.12.12'); // returns false
checkIpIsValid('123.12.12.12'); // returns true

javascript: is there any elegant way to check if string contains any of characters given in an array [duplicate]

This question already has answers here:
Call a function if a string contains any items in an array
(3 answers)
Closed 8 years ago.
I have a string in my JavaScript code (plain JavaScript, no jQuery or any other libs involved). And also I have an array which contains characters to be found in a string. I need to check if string contains any of those characters. Of course, it could be done with temporary variable like found and array elements iteration.
But is there any way to write nice and compact code? Just in case, I use ES5 (IE9+).
I want to achieve something like
var str = "Here is the string",
chars = ['z','g'];
if (str.containsAnyOf(chars)) {
...
}
What is the best way to write that piece of code?
You can use Array.prototype.some, like this
if (chars.some(function(c) { return str.indexOf(c) !== -1; })) {
// Atleast one of the characters is present
};
Consider using regular expression:
var str = "Here is the string",
chars = ['z','g'];
// constructs the following regexp: /[zg]/
if (new RegExp("[" + chars.join('') + "]").test(str)) {
alert("Contains!");
}

JS replacing all occurrences of string using variable [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 9 years ago.
I know that str.replace(/x/g, "y")replaces all x's in the string but I want to do this
function name(str,replaceWhat,replaceTo){
str.replace(/replaceWhat/g,replaceTo);
}
How can i use a variable in the first argument?
The RegExp constructor takes a string and creates a regular expression out of it.
function name(str,replaceWhat,replaceTo){
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
If replaceWhat might contain characters that are special in regular expressions, you can do:
function name(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
See Is there a RegExp.escape function in Javascript?
The third parameter of flags below was removed from browsers a few years ago and this answer is no longer needed -- now replace works global without flags
Replace has an alternate form that takes 3 parameters and accepts a string:
function name(str,replaceWhat,replaceTo){
str.replace(replaceWhat,replaceTo,"g");
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Categories

Resources