Convert string into Regular Expression in Javascript [duplicate] - javascript

This question already has answers here:
Building regexp from JS variables not working
(5 answers)
Closed 7 years ago.
From the backend of my application, I receive a regular expression which should be matched with a postal code in the frontend.
However, every time I convert to string into a regular expression using the RegExp class, I get another regular expression which doesn't match my postal code anymore.
This is the code I'm currently using (copy from my console):
var str = '/^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$/',
exp = new RegExp(str);
// Returns null
'1055AA'.match(exp);
// The code below does work though...
// Returns: ["1055AA", "AA"]
'1055AA'.match(/^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$/);
Can someone help me solve this problem? Thanks!

Your input string must not begin and end with the Regexp markers / - after all, it's a regular string, not a literal regexp. Also, since it's a regular string (and not (yet) a regexp), you need to double the backslashes as usual in a regular string.

Related

invalid Regex group [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
I'm trying to create the following regex using Javascript.
(?<!\\)(?:\\{2})*\\(?!\\)([5-9]|[1-9]\d)
However, by doing this it gives me invalid group error in the console.
regExp = new RegExp("(?<!\\)(?:\\{2})*\\(?!\\)([5-9]|[1-9]\d)", "gi");
I don't understand where the problem comes from exactly. I appreciate the help.
Thank you
EDIT: After some research I found that Javascript does not support lookbehinds.
So the error comes from (?<!\\).
Refer this newly asked question to find an alternative way to do the same job.
How to check for odd numbers of backslashes in a regex using Javascript?
If your expression isn't dynamic, just use a literal:
var regExp = /(?<!\\)(?:\\{2})*\\(?!\\)([5-9]|[1-9]\d)/gi;
The problem is that your escape sequences \\ inside the string end up rendering \ characters inside the regEx, which in turn end up escaping brackets they shouldn't, resulting in unterminated groups.

JavaScript special characters misunderstanding [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 8 years ago.
In this javascript code I have this row:
var regex = /\s+/gi;
Any idea what is the maning of this:
/\s+/gi
Thank you in advance.
Here is a must read for same https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec and test methods of RegExp, and with the match, replace, search, and split methods of String. This chapter describes JavaScript regular expressions.
Here, each contiguous string of space characters is being replaced with the empty string
For more details refer :-
Is there a difference between /\s/g and /\s+/g?

Wanted to check whether string ends with special character or not? [duplicate]

This question already has an answer here:
Need to do a right trim on ajax query in javascript?
(1 answer)
Closed 8 years ago.
I wanted to check whether my string which ends with special character or not. If my string contains special character at the end, then need to trim at the right. if not, do nothing.
My piece of code:
var s = 'acbd#';
var x = 'abcd#e'
Expected Result:
acbd
abcd#e
any help on this?
You can use regular expression to replace the special characters with empty string, like this:
s.replace(/[#]+$/, "");
x.replace(/[#]+$/, "");
You can specify more special characters inside of square brackets.

Javascript regex to extract the string before the last backslash [duplicate]

This question already has answers here:
Regex for everything before last forward or backward slash
(3 answers)
Closed 9 years ago.
I am dealing with timezone's in Javascript and I need a regex that will extract everything, but the timezone name from it. For example, I have the timezone America/Argentina/Buenos_Aires. I want to extract the America/Argentina part with a regex. Currently I have this regex: tz.match(/.*?(?=\/|$)/i)[0] which extracts everything to the first backslash which works for most timezones (America/Los_Angeles), but not for all of them. How could I edit that regex so that it gets the string before the last value?
I'd personally suggest avoiding regular expressions for something like this, when simple string functions/methods would suffice admirably:
var stringVariable = 'America/Argentina/Buenos_Aires',
text = stringVariable.substring(0, stringVariable.lastIndexOf('/'));

Javascript RegEx Not Working [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 2 years ago.
I have the following javascript code:
function checkLegalYear() {
var val = "02/2010";
if (val != '') {
var regEx = new RegExp("^(0[1-9]|1[0-2])/\d{4}$", "g");
if (regEx.test(val)) {
//do something
}
else {
//do something
}
}
}
However, my regEx test always returns false for any value I pass (02/2010). Is there something wrong in my code? I've tried this code on various javascript editors online and it works fine.
Because you're creating your regular expression from a string, you have to double-up your backslashes:
var regEx = new RegExp("^(0[1-9]|1[0-2])/\\d{4}$", "g");
When you start with a string, you have to account for the fact that the regular expression will first be parsed as such — that is, as a JavaScript string constant. The syntax for string constants doesn't know anything about regular expressions, and it has its own uses for backslash characters. Thus by the time the parser is done with your regular expression strings, it will look a lot different than it does when you look at your source code. Your source string looks like
"^(0[1-9]|1[0-2])/\d{4}$"
but after the string parse it's
^(0[1-9]|1[0-2])/d{4}$
Note that \d is now just d.
By doubling the backslash characters, you're telling the string parser that you want single actual backslashes in the string value.
There's really no reason here not to use regular expression syntax instead:
var regEx = /^(0[1-9]|1[0-2])\/\d{4}$/g;
edit — I also notice that there's an embedded "/" character, which has to be quoted if you use regex syntax.

Categories

Resources