How to escape special characters [duplicate] - javascript

This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 6 years ago.
I'm trying to create a regular expression to detect if the string has a special character.
/[!$&*-\=^`|~#%'+?{}._]+/.test('Hello2016'); // returns true when should return false because there's no special character
In the previous sample, it's returning true. I guess it's related to the = symbol but I don't know where it's the mistake.

It's actually because of the - character. Inside of a character class ([...]) it represents a range of characters. For example [a-f] would match a, b, c, d, e, or f.
The correct pattern would be:
/[!$&*\-=^`|~#%'+?{}._]+/
You haven't actually specified what you consider a 'special character', but a far simpler pattern would be:
/[^\W_]/
This will match an underscore or any character that's not a Latin letter or decimal digit (\W).

If you'd like to detect all special characters, validate that the string includes only the characters you want, that way special characters you did not account for get flagged as special characters. This makes your code applicable in more scenarios and makes it future proof.
if(!name.match(/^[a-zA-Z0-9]+$/i)) {
// handle the case where there are special characters in the string
}

You shoud escape regular expression's special charactors like this.
[!\$&\*\-\\=^`|~#%'\+\?{}\._]
These have special meaning in regular expression.
$*-\+?.
And maybe this also works.
!/^[A-Za-z0-9]+$/.test('Hello2016')

Related

Why is my regex allowing unspecified characters? JavaScript [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Difference between regex [A-z] and [a-zA-Z]
(6 answers)
Regular expression works on regex101.com, but not on prod
(1 answer)
Closed 2 years ago.
I know this question has been asked a few times and the answers are unique to the specific regexes in question, but aside from that, I've tried to make sure that I'm escaping characters that have special meaning. Whilst this regex plays ball on https://regex101.com (in JavaScript mode), in my app it's having other ideas!
^([A-z0-9][A-z0-9 '\-,\.:\&]{0,245}[A-z0-9]|[A-z0-9][A-z0-9 '\-,\.:\&]{1,244}[A-z0-9])$
This is what I tell the user: 2-247 characters, start and end with A-z 0-9, permitted special characters: ' - , . : &
...but as you see, I'm actually also ensuring that the string starts with:
a) Two non-special characters, or
b) One non-special character followed by a special character, as long as that special character is followed by one or more non-special characters.
This is how I'm implementing the regex:
var nameRegex = new RegExp("^([A-z0-9][A-z0-9 '\-,\.:&]{0,245}[A-z0-9]|[A-z0-9][A-z0-9 '\-,\.:&]{1,244}[A-z0-9])$");
if (!nameRegex.test(formElements[i].value)) {
// validation stuff here
}
Everything the regex intends on doing, it does. I've tested every condition that I'm checking for. But it does more. Regex 101 disallows a string like d*d, but my app? Perfectly fine.
I'll try .match instead of .test, maybe .test isn't the tool I think I need for this job?

Why does this regex not exclude hyphens or brackets? [duplicate]

This question already has answers here:
Why this javascript regex doesn't work?
(1 answer)
Match exact string
(3 answers)
Closed 5 years ago.
Regex is the bane of my existence. I've done plenty tutorials, but the rules never stick, and when I look them up they seem to conflict. Anyways enough of my whining. Could someone tell me why this regex doesn't exclude hyphens or brackets:
/^[A-Za-z_][A-Za-z\d_]*/
The way I understand it (or at least what I'm trying to do), the ^ character dictates that the regex should start with the next thing on the list That means the regex should start with [A-Za-z_] or any character a-z and A-Z as well as and underscore _. Then the string can have anything that includes [A-Za-z\d_] which is any alphanumeric character and an underscore. Then I use the * to say that the string can have any number of what was presented previously (any alphanumeric character plus underscore). At no point to I specify a bracket [ or a hyphen -. Why does this expression not exclude these characters
Extra info
I'm verifying this with javascript:
function variableName(name) {
const reg = RegExp("^[A-Za-z_][A-Za-z\d_]*")
return reg.test(name)
}
function variableName("va[riable0") // returns true should be false
It's actually matching the first 2 letters("va"), that's why it's true.
To match the whole phrase, your reg expression should have "$" at the end:
"^[A-Za-z_][A-Za-z\d_]*$"
Your regex matches the part of the string that does not contain the bracket, because your're missing the $ anchor that would (together with ^) force it to match the whole string. Use
const reg = /^[A-Za-z_][A-Za-z\d_]*$/g
// ^
function variableName(name) {
return reg.test(name)
}
console.log(variableName("va[riable0"))

validation using \p{L} in JavaScript regexp [duplicate]

This question already has answers here:
Match only unicode letters
(3 answers)
Closed 4 years ago.
**var pattern = /^[\p{L}0-9 ##'!&(),\[\].+/-]{1,100}$/;** \\first of all I din understand this pattern. someone plz explain it to me\\
if (!pattern.test(Name))
{
alert('Account Name must not contain the given values');
Xrm.Page.getAttribute("name").setValue("");
return false;
}
else
{
return true;
}
when I give this as validation it is throwing error message for all the values I enter. So I need some explanation on the pattern which I think will solve the rest.
In Javascript, the sequence \p{L} (in a character class) has no special meaning; it simply means the letter p or the letter { or the character L or the character }. You're probably getting confused with XRegExp, another library, or another language's (eg Perl, PHP, .NET etc.) implementation of regexps, which support so-called Unicode character categories.
Change
/^[\p{L}0-9 ##'!&(),\[\].+/-]{1,100}$/
to
/^[\p{L}0-9 ##'!&(),\[\].+\/-]{1,100}$/
^^
since you have to escape slashes / since you have defined them to be delimiters.
The meaning of the regex is that your entire string has to be between 1 and 100 characters of the listed characters, numbers and letters.

How do I include an inline comment in a regular expression in JavaScript [duplicate]

This question already has answers here:
Commenting Regular Expressions
(7 answers)
Closed 3 years ago.
Inline comments works when a string passed to the RegExp constructor:
RegExp("foo"/*bar*/).test("foo")
but not with an expression. Is there any equivalent or alternative in JavaScript to emulate x-mode for the RegExp object?
Javascript supports neither the x modifier, nor inline comments (?#comment). See here.
I guess, the best you can do, is to use the RegExp constructor and write every line in e separate string and concatenate them (with comments between the strings):
RegExp(
"foo" + // match a foo
"bar" + // followed by a bar
"$" // at the end of the string
).test("somefoobar");
Other than using a zero-length sub-expression, it's not possible. Examples of "comments":
/[a-z](?!<-- Any letter)/
(?!..) is a negated look-ahead. It matches if the previous is not followed by the string within the parentheses. Since the thing between (?! and ) is a real regular (sub)expression, you cannot use arbitrary characters unless escaped with a backslash
An alternative is to use the positive look-ahead:
/[a-z](?=|<-- Any letter)/
This look-ahead will always match, because obviously the a-z is also followed by an empty string.

JavaScript: \\d{4} RegExp allows more than 4 digits [duplicate]

This question already has answers here:
Match exact string
(3 answers)
Closed 4 years ago.
Have following validation for year value from text input:
if (!year.match(new RegExp('\\d{4}'))){
...
}
RegExp equals null if numeric of digits from 0 to 3. It's OK.
In case 4 digits it returns value.It's OK.
In case more than 4 digits it returns value again,that it's NOT OK.
Documentation says {n} declaration means exact number,but works like:
exact+
With such ugly validation it work's fine:
if (!year.match(new RegExp('\\d{4}')) || year.length>4){
...
}
I wish to utilize RegExp object only.
Yes it would allow more than 4 digits since it would be a partial match use the ^ and $ to mark the beginning and the end of the string.
if (!year.match(new RegExp('^\\d{4}$'))){
...
}
If you include ^ in your regex it matches the beginning of the string, while $ matches the end, so all up:
^\d{4}$
Will match only against beginning-of-string plus four digits plus end-of-string.
Note that regex literal syntax is generally a bit simpler than saying new Regex():
/^\d{4}$/
// is the equivalent of
new RegExp('^\\d{4}$')
Note that in the literal syntax you don't have to escape backslashes like with the string you pass to the new RegExp(). The forward slashes are not part of the expression itself, you can think of them like quotation marks for regexes.
Also, if you just want to check if a string matches a pattern (yes or no) without extracting what actually matched you should use the .test() method as follows:
if (!/^\d{4}$/.test(year)) {
...
}
It's matching the first four digits and then the fact that there's any remaining digits it neither here nor there. You need to change your regex so it stops after these four digits, say, by using the string termination anchors:
^\d{4}$
Try instead:
'^\\d{4}$'
What you had will match anything with 4 digits anywhere, such as asd1234asd or 123456789

Categories

Resources