Regex for special characters working wrong [duplicate] - javascript

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 regex for checking if password got special characters.
https://www.owasp.org/index.php/Password_special_characters
It looks like this
new RegExp('[!##\$%\^\&*\)\(+=._\'",/<>?[\\\]`{|}~:;-\s]', 'g');
Unfortunately is also catching bare words: reg.test('word') it returns true.
Whats wrong with my regex?

You didn't escape properly. RegExp object could receive a regular expression as a string but escaping matters: it needs double backslashes.
For now [;-\s] is equal to [;-s] which includes 57 characters:
[_;?\[\]#\\`\^<->aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsS-Z]
However, it should be [;\-\\s].

You can use negative/inverse logic and test against any character that is not a number or a letter.
Using [^A-Za-z0-9] where caret (^) matches everything except A-Za-z0-9.
const regex = /([^A-Za-z0-9]|[.\p{L}])/gm;
console.log('word: ' + regex.test('word'));
console.log('word!: ' + regex.test('word!'));
console.log('!£2word!: ' + regex.test('!£2word!'));
console.log('!ą,ć,ó!"£wordąćó: ' + regex.test('!ą,ć,ó!"£wordąćó'));

Related

Removing all occurrences of '^' from a String [duplicate]

This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
Closed 2 years ago.
I have this sorta string = "^My Name Is Robert.^"
I want to remove the occurrences of ^ from this string. I tried the replace method like :
replyText.replace(/^/g, '');
But it hasn't any affect. Using the replace without the global works but only removes the first occurrence.
Should I just make a loop and keep looping the string with replace till no more '^' are contained, or is there a better way?
You need to escape the ^ character in RegEx:
replyText.replace(/\^/g, '');
The caret, ^, is a special character in Regex, therefore it has to be escaped with a backslash i.e
replyText.replace(/\^/g, '')

How replace all "/" to "-" in a string using Javascript [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 3 years ago.
I have a string like
abcd/123/xyz/345
I want to replace every "/" with "-" using JavaScript.
The result string should be abcd-123-xyz-345
I have tried,
string.replace("/","-")
But it replaces the first "/" character only. The result is abcd-123/xyz/345
And
string.replace("///g","-");
is not working as well.
Is there any solution for this?
You can use Regex. You need to escape using backslash \ before the /.
A backslash that precedes a special character indicates that the next character is not special and should be interpreted literally
var str = 'abcd/123/xyz/345';
let result = str.replace(/\//g,'-');
console.log(result);
Please try this,
var str='abcd/123/xyz/345'
var newstr=str.split('/').join('-');
console.log(newstr)

Javascript Regex multi space "\s" doesn't work in chrome [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 6 years ago.
I try to use this Regex
new RegExp('utm_source=Weekly\SRecommended\SJobs\SEmail', 'ig');
When I try to use it in regex101 or regexr it works.
And in my code doesn't work.
I try to use this in console this is the result is
/utm_source=WeeklysRecommendedsJobssEmail/gi
the code without spaces.
When I try to use space letter it works.
Any help?
Because \ is an escape character for regular expressions and strings. You have to escape the \ if you're creating a regex from a string:
new RegExp('utm_source=Weekly\\SRecommended\\SJobs\\SEmail', 'ig');
Or simply use a regex literal which exists precisely to avoid this problem:
/utm_source=Weekly\SRecommended\SJobs\SEmail/ig

How exactly does this RegEx and replace work in JavaScript? [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 7 years ago.
I have the following code:
var fileName = "C:\fakepath\a.jpg";
fileName = fileName.replace(/.*(\/|\\)/, '')
and this will return just the a.jpg as intended but I don't understand how it knew to replace the the characters between both of "\" such as the substring "fakepath". From what I see it should just replace the first character "C" because of the period and then any appearances of "/" or "\" with "".
The . means any character.
The * means zero or more.
So .* matches from the start of the string to the point where matching any more characters would prevent the rest of the regular expression from matching anything.

why does this regular expression always return null? [duplicate]

This question already has answers here:
Check if an element contains a class in JavaScript?
(30 answers)
Closed 9 years ago.
I need to check for classname in a string.
My string looks like this:
testing ui-li ui-li-static ui-btn-up-f ui-first-child ui-filter-hidequeue
And I'm looking for ui-filter-hidequeue anywhere (!) in the string.
This is what I'm trying. It always returns null, althought the string I'm trying to match is there:
var classPassed = 'ui-filter-hidequeue',
classes = 'testing ui-li ui-li-static ui-btn-up-f ui-first-child ui-filter-hidequeue',
c = new RegExp('(?:\s|^)' + classPassed + '(?:\s|$)');
console.log( classes.match(c) ) // returns null
Question:
Can someone tell me what I'm doing wrong in my regex?
Thanks!
You need \\s. \s inside a string would escape the s, which does not need escaping, and evaluates to just a "s". I.e. when you're using literal regexps, backslash escapes the regexp characters; and strings also use backslash to escape string characters. When you build a regexp from a string, you need to think about both of these layers: \\ is string-escapey way of saying \, then \s is the regexp-escapey way of saying whitespace.
Also as other comments show, there are WAY better ways to test for class presence. :) But I just answered the direct error.
Try using this:
c = new RegExp('\\b' + classPassed + '\\b');
The \b metacharacter matches at the beginning/end of a word; it stands for boundary (as in, word boudnary).

Categories

Resources