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
Related
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 2 years ago.
problem:
I want to remove the comma in a string and make it as a number.
It means,
234,345 should become 234345.
1,234 should become 1234
4,567,890 should become 4567890
I have created one code like this.
let a = "5,245"
function numberWithoutCommas(x) {
return x.replace(",","");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)
This is failing when there more comma in the string.It means 1,234,567 gives 1234. So can someone help me to achieve it?
Splitting and joining should do the job
return x.split(',').join('');
You can simply parse to a number and use a regex
const s = ['5,332', '39,322,322,233']
function numberWithoutCommas(x) {
return Number(x.replace(/,/g, ''));
}
for (const a of s) {
const n = numberWithoutCommas(a);
console.log(n, typeof n);
}
passing string as a first argument to replace method will only replace the very first occurrence.
let str = '111,11,11,1';
str.replace(',','') // result:- 11111,11,1
use regex instead
str.replace(/,/g,'') //result:- 11111111
in your use case
function numberWithoutCommas(x) {
return x.replace(/,/g,"");
}
The replace() method searches a string for a specified value, or a
regular expression, and returns a new string where the specified
values are replaced.
Note: If you are replacing a value (and not a regular expression),
only the first instance of the value will be replaced. To replace all
occurrences of a specified value, use the global (g) modifier.
So, to replace all the occurrences of ,, we should rather use /,/g instead of just ,.
Then your code would be something like the following
let a = "1,234,567"
function numberWithoutCommas(x) {
return x.replace(/,/g,"");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)
I hope this helps :)
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.
This question already has answers here:
Match exact string
(3 answers)
Regex created via new RegExp(myString) not working (backslashes)
(1 answer)
Difference in results between Java matches vs JavaScript match
(3 answers)
Closed 4 years ago.
The regular expression is "(\d+)|(N\A)", which matches digits or string "N\A". It works in Java, but not in JavaScript.
Results are different between Java and JavaScript.
Results of two versions in JavaScript are different.
What's wrong I made?
Code code snippet:
Java
Environment: JDK 1.8.0_144
String orderNumberRegExp = "(\\d+)|(N/A)";
System.out.println("12345".matches(orderNumberRegExp));
String digitalOnly = "\\d+";
System.out.println("12345".matches(digitalOnly));
System.out.println("12345ABC".matches(digitalOnly));
Output (as my expected):
true
true
false
JavaScript
Environment: node v9.8.0
The two versions return wrong results both.
Version 1:
var orderNumberRegExp = new RegExp("(\d+)|(N\/A)"); // or "(\d+)|(N/A)"
console.log(orderNumberRegExp.test("12345"));
var digitalOnly = new RegExp("\d+");
console.log(digitalOnly.test("12345"));
console.log(digitalOnly.test("12345ABC"));
Output:
false
false
false
Version 2:
var orderNumberRegExp = /(\d+)|(N\/A)/
console.log(orderNumberRegExp.test("12345"));
var digitalOnly = /\d+/;
console.log(digitalOnly.test("12345"));
console.log(digitalOnly.test("12345ABC"));
Output:
true
true
true
Thanks for all your help. My code has issues:
When to create regular expression using RegExp(), the backslash should be escaped. (#LukStorms, #grzegorz-oledzki, and #benny)
(Also Ref to the demo from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
The test method is different from the matches method in Java. It should add ^ and $ to assert the start and end of the string. (More details in the answer by #sweeper )
So, code can be:
var orderNumberRegExp = new RegExp("^(\\d+)$|^(N/A)$");
console.log(orderNumberRegExp.test("12345")); // true
console.log(orderNumberRegExp.test("N/A")); // true
console.log(orderNumberRegExp.test("12345ABC")); // false
console.log(orderNumberRegExp.test("ABC1234")); // false
var digitalOnly = new RegExp("^\\d+$");
console.log(digitalOnly.test("12345")); // true
console.log(digitalOnly.test("12345ABC")); // false
The regular expressions can also be:
var orderNumberRegExp = /^(\d+)$|^(N\/A)$/
var digitalOnly = /^\d+$/
The test method is different from the matches method in Java.
RegEx.prototype.test() returns true whenever a match is found in the string, whereas Matcher.matches() returns true only if the whole string matches the pattern. So the JavaScript test() is more similar to the Java Matcher.find() than to Matcher.matches().
To make your Javascript regexes work, you need to add ^ and $ to assert the start and end of the string:
var orderNumberRegExp = /^(?:(\d+)|(N\/A))$/
console.log(orderNumberRegExp.test("12345"));
var digitalOnly = /^\d+$/;
console.log(digitalOnly.test("12345"));
console.log(digitalOnly.test("12345ABC"));
This will simulate the behaviour of Matcher.matches()
Try var digitalOnly = new RegExp("\\d+");
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.
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