How to use '\' in the regular expression extjs - javascript

I am using this regular expression: [a-zA-Z0-9\-.,:+*()=\'&_], but i am getting error like :'unterminated character class' error in this expression':
Demo Code:
Ext.getCmp('field2').addListener({
beforequery: function (e) {
if (e.query && e.query.indexOf('?') != -1) {
var temp = '';
for(var i=0;i<e.query.length;i++){
temp = temp + '['+e.query[i]+ ']';
}
e.cancel = true;
var query = new RegExp(String.format('^{0}',temp.replace(/\?/g, 'a-zA-Z0-9\.,:\+*()=\'&_-\\')));
this.expand();
this.store.clearFilter(true);
this.store.filter(this.displayField, query);
}
}
});
Errors:
1.Please someone tell me whats wrong in this, mainly with backslash.
2.when we enter desired characters in combobox they are being selected automatically..so when we want to enter new character we have to press side arrow or else remaining characters are being deleted...
Thanks once again,
Raj

I think you have to escape some of the items in your character class. Like your backslash, asterisk, plus, parenthesis and period.
Something like this [a-zA-Z0-9\\-\.,:\+\*\(\)=\\'&_]
Adding a backslash to special characters [\^$.|?*+(){} in a regular expression suppresses their special meaning which allows you to use them literally.
http://www.regular-expressions.info/reference.html

In the regex there are 11 characters you need to escape: the opening square bracket [, the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening round bracket ( and the closing round bracket ).

You need to escape some characters in your regular expression. So it would look like:
var regex = /[a-zA-Z0-9\-\.,:\+\*\(\)=\\'&_]/; // Note the backslashes
Parentheses, the plus sign, the asterisk, and the backslash are some of the many characters that have a special meaning in regular expressions. In order to include them literally, you need to escape them with a backslash.

Related

How to stop regex conflicting with : in bootstrapValidate plugin

I am using the following regex with bootstrapValidate plugin to validate a field.
bootstrapValidate('#input', 'regex:/^(my:track:[a-zA-Z0-9]{22}$)/:Invalid input')
The docs state to use this expression:
bootstrapValidate('#input', 'regex:^[a-z]+$:Please fulfill my regex')
The issue is I am using : inside the regex match and conflicts with the separator options.
How can I stop the : regex conflicting? Thanks!
http://www.w3processing.com/index.php?subMenuLoad=javascript/RegExp/RegExpUsing.php
This site says colon is a control character which must be escaped with a backslash (quoted below).
If you want to include any of these characters literally in a regular
expression, you must precede them with the backslash character \
(escape character).
var pattern1 = /\\/; \\ match backslash character
var pattern2 = /\[/; \\ match starting square brackets
var pattern3 = /\:/; \\ match colon character

Can't replace "[" and "]" characters in a string in Javascript

I'm trying to replace "[" and "]" characters in the string using javascript.
when I'm doing
newString = oldString.replace("[]", "");
then it works fine - but the problem is I have a lot of this characters in my string and I need to replace all of the occurrences.
But when I'm doing:
newString = oldString.replace(/[]/g, "");
or
newString = oldString.replace(/([])/g, "");
nothing is happens. I've also tried with HTML numbers like
newString = oldString.replace(/[]/g, "");
but it doesn't work neither. Any ideas how to make it?
You either need to escape the opening square bracket, and add a pipe between them:
newString = oldString.replace(/\[|]/g, "");
Or you need to add them in a character class (square brackets) and escape them both:
newString = oldString.replace(/[\[\]]/g, "");
DEMO
"...there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {... If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash."
[] in a regex is a character class. Since you haven't escaped, them you're saying a "find any of the following characters", and not providing any. Try /[\[\]]/ instead.
edit: #andy is right. forgot to put in a container [].
This is a simple solution :
newString = oldString.split("[]").join("");
had a similair situation. i just used backslash like so.
-replace '\[','' -replace ']',''

Regex to allow certain special characters - escape issue

I've working on a javascript regex that I intend to use with the jquery validate plugin (I'll add this as an additional method). It must (among other rules):
test if at least one of the following special characters is entered:
!, ", #, $, %, &, ', (, ), *, +,-, .,/, :, ;, <, =, >, ?, #, [, \, ], ^, _, `, {, |, }, ~
not allow 3 consecutive identical characters:
passed:
aa
99
++
not passed:
aaa
999
+++
The problem with my regex is that is having problem with these mentioned rules:
I think the issue is related to escaping and I've tried escaping + and - to no avail. Can anyone help! This is my regex: http://regexr.com/3ack3
This is one of those requirements where you can really simplify your life by using multiple regexes, rather than trying to cram all the logic into one complex regex with many assertions. Here's some JavaScript that implements your requirement:
var specialCharRegex = /[!"#$%&'()*+.\/:;<=>?#\[\\\]^_`{|}~-]/;
var threeConsecutiveRegex = /(.)\1\1/;
var input = prompt();
if (specialCharRegex.test(input) && !threeConsecutiveRegex.test(input)) {
alert('passed');
} else {
alert('failed');
} // end if
http://jsfiddle.net/t8609xv2/
Some notes on the trickier points:
inside the bracket expression, the following four special characters had to be backslash-escaped: /[\]. (Forward slash because it delimits the regex, backslash because it's the escape character, and the brackets because they delimit the bracket expression.)
inside the bracket expression, the dash had to be moved to the end, because otherwise it would likely specify a character range. When at the end, it never specifies a range, so it's always safer to put it there.
This modular approach also benefits maintainability, as you will more easily be able to make changes (modify/add/remove regexes, or change the if-test logic) at a later point in time.
Another benefit is that you could test each regex independently, which could allow you to provide a more accurate error message to the user, as opposed to just saying something like "invalid password".
Edit: Here's how you can whitelist the chars that are accepted in the input:
var specialCharRegex = /[!"#$%&'()*+.\/:;<=>?#\[\\\]^_`{|}~-]/;
var threeConsecutiveRegex = /(.)\1\1/;
var nonWhitelistCharRegex = /[^a-zA-Z0-9!"#$%&'()*+.\/:;<=>?#\[\\\]^_`{|}~-]/;
var input = prompt();
if (specialCharRegex.test(input) && !threeConsecutiveRegex.test(input) && !nonWhitelistCharRegex.test(input)) {
alert('passed');
} else {
alert('failed');
} // end if
http://jsfiddle.net/t8609xv2/2/
^(?=.*[!"#$%&'()*+,,\/:;<=>?#\[\]^_`{|}~-])(?!.*(.)\1\1).*$
Try this.See demo.
https://regex101.com/r/wX9fR1/10
You need a positive lookahead to check for special characters.
And
A negative lookahead to check if a character is is there 3 times.
You can use this regex:
^(?!.*?(.)\1{2})(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*?[!##$%^&*()_=\[\]{};':"\\|,.<>\/?+-]).{8,20}$
RegEx Demo
You might be able to shorten it using:
^(?!.*?(.)\1{2})(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*?[\W_]).{8,20}$
i.e. using non-word property \W instead of listing each and every special character.

Javascript regex only alphabet, number and underscore

I want to check if a text box input is valid (only alphabet, numbers and underscores allowed. No whitespaces or dashes). I currently have this, but whitespaces & dashes seem to pass.
function validText(field)
{
var re = /[a-zA-Z0-9\-\_]$/
if (field.value.search(re) == -1)
{
alert ("Invalid Text");
return false;
}
}
A valid input would be something like
'Valid_Input123'
invalid
'Invalid-Input !'
The \w is a handy regex escape sequence that covers letters, numbers and the underscore character
You should test the entire string for valid characters by anchoring the validity test at the start (^) and end ($) of the expression
The regular expression test method is faster than the string search method
You can also test for one or more characters using the + quantifier
To summarise (in code)
var re = /^\w+$/;
if (!re.test(field.value)) {
alert('Invalid Text');
return false;
}
return true;
Alternatively, you can test for any invalid characters using
/\W/.test(field.value)
\W being any character other than letters, numbers or the underscore character.
Then you might also need to add a length check to invalidate empty strings, eg
if (/\W/.test(field.value) || field.value.length === 0)
You are only testing whether the text ends ($) with one of the characters in the character class. You are also explicitly allowing a dash (\-). If you don't want that, remove it.
Anchor the expression (^, $), add a quantifier (+) and .test whether the string only consists of those characters:
var re = /^[a-zA-Z0-9_]+$/; // or /^\w+$/ as mentioned
if (!re.test(field.value)) {
}
You forgot to anchor your regex at the beginning using ^
test is easier to use
There is no need for the dash.
It should look like this:
if (!/^[a-z0-9_]+$/i.test(field.value)) {
//
}
[\w]* will suffice.
Regex101 Example
This is a very basic Regular Expressions question
Learn more about regular expressions here: regular-expressions.info

javascript regex for special characters

I'm trying to create a validation for a password field which allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
I can't seem to get the hang of it.
What's the difference when using regex = /a-zA-Z0-9/g and regex = /[a-zA-Z0-9]/ and which chars from .!##$%^&*()_+-= are needed to be escaped?
What I've tried up to now is:
var regex = /a-zA-Z0-9!##\$%\^\&*\)\(+=._-/g
but with no success
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]+$/g
Should work
Also may want to have a minimum length i.e. 6 characters
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]{6,}$/g
a sleaker way to match special chars:
/\W|_/g
\W Matches any character that is not a word character (alphanumeric & underscore).
Underscore is considered a special character so
add boolean to either match a special character or _
What's the difference?
/[a-zA-Z0-9]/ is a character class which matches one character that is inside the class. It consists of three ranges.
/a-zA-Z0-9/ does mean the literal sequence of those 9 characters.
Which chars from .!##$%^&*()_+-= are needed to be escaped?
Inside a character class, only the minus (if not at the end) and the circumflex (if at the beginning). Outside of a charclass, .$^*+() have a special meaning and need to be escaped to match literally.
allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
Put them in a character class then, let them repeat and require to match the whole string with them by anchors:
var regex = /^[a-zA-Z0-9!##$%\^&*)(+=._-]*$/
You can be specific by testing for not valid characters. This will return true for anything not alphanumeric and space:
var specials = /[^A-Za-z 0-9]/g;
return specials.test(input.val());
Complete set of special characters:
/[\!\#\#\$\%\^\&\*\)\(\+\=\.\<\>\{\}\[\]\:\;\'\"\|\~\`\_\-]/g
To answer your question:
var regular_expression = /^[A-Za-z0-9\!\#\#\$\%\^\&\*\)\(+\=\._-]+$/g
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters
There are some issue with above written Regex.
This works perfectly.
^[a-zA-Z\d\-_.,\s]+$
Only allowed special characters are included here and can be extended after comma.
// Regex for special symbols
var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.##]/;
This regex works well for me to validate password:
/[ !"#$%&'()*+,-./:;<=>?#[\\\]^_`{|}~]/
This list of special characters (including white space and punctuation) was taken from here: https://www.owasp.org/index.php/Password_special_characters. It was changed a bit, cause backslash ('\') and closing bracket (']') had to be escaped for proper work of the regex. That's why two additional backslash characters were added.
Regex for minimum 8 char, one alpha, one numeric and one special char:
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[!##$%^&*])[A-Za-z\d!##$%^&*]{8,}$/
this is the actual regex only match:
/[-!$%^&*()_+|~=`{}[:;<>?,.##\]]/g
You can use this to find and replace any special characters like in Worpress's slug
const regex = /[`~!##$%^&*()-_+{}[\]\\|,.//?;':"]/g
let slug = label.replace(regex, '')
function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}
This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.
This works for me in React Native:
[~_!##$%^&*()\\[\\],.?":;{}|<>=+()-\\s\\/`\'\]
Here's my reference for the list of special characters:
https://owasp.org/www-community/password-special-characters
If we need to allow only number and symbols (- and .) then we can use the following pattern
const filterParams = {
allowedCharPattern: '\\d\\-\\.', // declaring regex pattern
numberParser: text => {
return text == null ? null : parseFloat(text)
}
}

Categories