Regular Expression to check Special characters except hypen and forwardslash [duplicate] - javascript

This question already has answers here:
Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./
(7 answers)
Closed 3 years ago.
I would like to know regex code to check whether it contains Special characters other than hypen and forwardslash in javascript
function containsSpecialCharacters(str){
var regex = /[~`!#$%\^&*+=\-\[\]\';,/{}|\\":<>\?]/g;
return regex.test(str);
}
var result = containsSpecialCharacters("sample"); // false
var result = containsSpecialCharacters("sample-test"); // false
var result = containsSpecialCharacters("sample++"); // true
var result = containsSpecialCharacters("/sample/test"); // false

You can use a normal regex to search for all ASCII special characters, like this one, and then just remove the hypen and backslash:
/[!$%^&*()_+|~=`{}\[\]:";'<>?,.]/
If you want to avoid any other special character, you just have to remove it from the regex.
You can test this regex here: https://regex101.com/r/gxYiGp/2

If you need to support only English characters, it would be far easier to list the exceptions than those you wish to match:
/[^\w\s\\\-]/.test(myString);
As noted, though, this will fail if you need to support international characters.

you can just negate it so it looks shorter, like this :
[^\s\w-]

Related

Regex special characters by ascii [duplicate]

This question already has answers here:
How do I use a Regex to replace non-alphanumeric characters with white space?
(1 answer)
Check for special characters in string
(12 answers)
Closed 3 years ago.
I have to use regex for my password validation that include special characters at least one.
https://en.wikipedia.org/wiki/ASCII
export const passwordValidation = password => {
const regPassword = /^(?=.*?[#?!#$%^&*-]).{8,}$/
return regPassword.test(password)
}
I tried this way but I think this isn't good way.
Is there other way to check all special characters by ascii code except alphanumeric ?
First, you need to define what a "special" character is. Do you mean anything not in the range A-Z (English alphabet)? A-Z and 0-9? Something else? Then you either use a character class listing the ones you want, which is what you've done, or a negated class saying you want something other than what's in the class:
return /^(?=.*?[^a-z0-9]).{8,}$/i.test(password);
// ^---- negated

Javascript Regex replace [] [duplicate]

This question already has answers here:
How can I put [] (square brackets) in RegExp javascript?
(8 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 4 years ago.
I am trying to replace the following in a Regex:-
[company-name]
Using Regex I would expect I could use was to use:-
str.replace(/[company-name]/g, 'Google');
But I know that the regex will replace any matching letter.
How am I able to replace the [company-name] with Google using JS Regex?
Thanks in advance for your help.
But I know that the regex will replace any matching letter.
This is only the case because you have encapsulated your characters in a character class by using [ and ]. In order to treat these as normal characters, you can escape these using \ in front of your special characters:
str.replace(/\[company-name\]/g, 'Google');
See working example below:
const str = "[company-name]",
res = str.replace(/\[company-name\]/g, 'Google');
console.log(res);
You need to escape the starting [ as well, in this case as they are special characters too:
var str = "I am from [company-name]!";
console.log(str.replace(/\[company-name]/gi, "Google"));
str = "[company-name]'s awesome!";
console.log(str.replace(/\[company-name]/gi, "Google"));
you could do it this way :
var txt = "So I'm working at [company-name] and thinking about getting a higher salary."
var pattern = /\[.+\]/g;
console.log(txt.replace(pattern, "Google"))
You should escape special characters like square brackets in this case.
Just use:
str.replace(/\[company-name\]/g, 'Google');

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"))

Regular Expression Maximum Number Of Characters Javascript [duplicate]

This question already has an answer here:
Restricting character length in a regular expression
(1 answer)
Closed 6 years ago.
So i have this regex:
var regex = /^[\S]+(\-[\S]+)$/
i want to add one more rule, the rule is that maximum number of characters is 6 or something, how do i do it? my full code looks like this
var regex = /^[\S]+(\-[\S]+)$/
var word = "a-a";
if(word.match(regex)){
console.log("matched");
}else{
console.log("did not match");
}
console.log(word.length);
i've tried var regex = /^([\S]+(\-[\S]+)){6}$/ but this means they must repeat a-a 6 times, i want the maximum number of characters, something like this:
var word = "123-56"
to be matched, how do i do it?
and i don't want to use .length because i want to implement it into regex
You can use a lookahead:
var regex = /^(?=.{0,6}$)[\S]+\-[\S]+$/

JavaScript regex for string literal? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a RegExp.escape function in Javascript?
I'm currently using: var keywords = new RegExp(req.params.keywords, 'i');
The catch is, if req.params.keywords == '.*', this will match anything, what I want is for it to match .* literally, as in \.\*\
Is there a more elegant solution than escaping every passed single character with a \?
If you want to match literally, instead of using the regular expressions included in the string, don't use a regular expression. Use the string indexOf() function to see if a string is contained withing another one.
For case insensitive matching, you convert each string to, say, lower case before the match.
var searchForString = req.params.keywords.toLowerCase();
var searchInString = xxx.toLowerCase();
if (searchInString.indexOf(searchForString) >= 0) {
... then it matches ...
}

Categories

Resources