validate string which has only one special character using javascript - javascript

I know there are several question like this on Stack-overflow, but I can't seem to get a straight answer out of the questions already posted.Looking forward if someone can help me.
I want to validate a string & return TRUE if it satisfies below condition
String contains only one special character i.e _ (underscore)
& this special character should not appear at beginning or end of the string
Example:
var demo1="23dsfXXXa32_XXXX" // Valid, should returns TRUE
var demo2="_23dsfXXXa32_XXXX" // Invalid,should returns FALSE
var demo3= "23dsfXXXa32XXXX_" //invalid,should returns FALSE
var demo4= "_" //invalid,should returns FALSE
var demo5= "&sdfsa_XX";// returns false
Tried: FIDDLE
if(/^[a-zA-Z0-9_ ]*$/.test(demo1) == true) {
alert('Valid String');
}
Result: Not functioning as per expected

Since you've said you require that the character be there, one way is to do it with a regular expression is with a negated character class at each end with a non-negated one in the middle:
var rex = /^[^_]+[_][^_]+$/;
That only handle underscores; add other "special" characters to all three character classes there.
How that works:
^ matches start of string
[^_]+ requires one or more characters not in the class
[_] requires exactly one character in the class
[^_]+ requires one or more characters not in the class
$ matches end of string

You could simplify it by using indexOf to verify that its not in the first or last position and split to see if its there only once. This is usually faster than a regex pattern.
function checkString(str){
return str.indexOf("_") !== 0 && str.indexOf("_") !== str.length-1 && str.split("_") === 2;
}

Related

Allowed Characters Regex (JavaScript)

I'm trying to build a regex which allows the following characters:
A-Z
a-z
1234567890
!##$%&*()_-+={[}]|\:;"'<,>.?/~`
All other characters are invalid. This is the regex I built, but it is not working as I expect it to. I expect the .test() to return false when an invalid character is present:
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*/g
return regex.test(string);
}
In this case, the test is always returning "true", even when "^" is present in the string.
Your regex only checks that at least one of the allowed characters is present. Add start and end anchors to your regex - /^...$/
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g
return regex.test(string);
}
... another approach, is instead of checking all characters are good, to look for a bad character, which is more efficient as you can stop looking as soon as you find one...
// return true if string does not (`!`) match a character that is not (`^`) in the set...
return !/[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/.test()
Instead of searching allowed characters search forbidden ones.
var string = 'abcd^wyd';
function regTest (string) {//[^ == not
var regex = /[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/g
return !regex.test(string);//false if found
}
console.log(regTest(string));
The regex, as you've written is checking for the existence of the characters in the input string, regardless of where it appears.
Instead you need to anchor your regex so that it checks the entire string.
By adding ^ and $, you are instructing your regex to match only the allowed characters for the entire string, rather than any subsection.
function isValidPassword (pwd) {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g\;
return regex.test(pwd);
}
alert(isValidPassword('abcd^wyd'));
Your regexp is matching the first part of o=your string i.e. "abcd" so it is true . You need to anchor it to the start (using ^ at the beginning) and the end of the string (using $ at the end) so your regexp should look like:
^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]$
That way it will need to match the entire string.
You can visualize it in the following link:
regexper_diagram
This regex will work.
var str = 'eefdooasdc23432423!##$%&*()_-+={[}]|:;"\'<,>.?/~\`';
var reg = /.|\d|!|#|#|\$|%|&|\*|\(|\)|_|-|\+|=|{|\[|}|]|\||:|;|"|'|<|,|>|\.|\?|\/|~|`/gi;
// test it.
reg.test(str); //true
I use this site to test my regex.
Regex 101

Regular expression matching javascript

I have a variable which can get any of the below values. x represents any alphanumeric character and the string can be of any length
/xxxxxxx
/xxxx/xxxx?xxx=xx
/xxxxx/
/xxxxxxxxx?
/xxxxxxx/xxxx/xxx
/xx/xxx.jpg
/xxx/xxxx/xxxx/xxxx
/xxx/xxxx/xxx/xxx/xxxx
/xxxx?xx=yy&abc=def&xyz=lmn
The goal is to get everything before the "?" character in the string if ? character exists
if it doesn't exist then it should simply get the string
i have written a regular expression as follows:
var pattern = /\/.*\?/;
The only issue is this pattern does not stop at the ? and return the whole string. Any clues how this can be fixed ?
The goal is to get everything before the "?" character in the string if ? character exists if it doesn't exist then it should simply get the string
/^[^?]*/
This works because ^ means start of input, and [^?] means a character that is not a ?, and * means zero or more, so the whole means "starting from input, zero or more characters that are not question marks".
That has the effect of matching from the start of the input to the first question mark or the end of input whichever comes first.
Something like this should work...
var pattern = /\/.*?(\?|$)/;
You don't really need a regex here, you could simply use indexOf() and substr():
var qPos = url.indexOf('?');
var path = (qPos === -1) ? url : url.substring(0, qPos);

Regex if string contains E or F letter

I'm trying to check if a string contains specific letters like E or F, with the following code
/^(F?)/.test('E22')
The problem is that it returns true, when it should return false. And what bothers me most, is that testing the regex at regexpal.com, goes perfect, but when applied... wrong.
Any idea what goes wrong?
http://jsfiddle.net/alleks/CykQv/
UPDATE
I have explained my self wrong. I do individual checks, in different cases. So, in specific cases I need to see if the string contains an E, and in others, if contains an F
//Case1
if (/^(F?)/.test(stringContainsE)) ....
//Case2
if (/^(F?)/.test(stringContainsF)) ....
Update2
Both cases return TRUE when they shouldn't: http://jsfiddle.net/alleks/CykQv/2/
The question mark makes the F optional. That regex will return true for every single string.
/[EF]/
Will match strings that contain a letter E and/or a letter F.
EDIT: As Paul mentioned in his comment, the ^ character matches the beginning of the string. If the character must occur at the beginning of the string then:
/^E/
will test for an E at the beginning of the string. Simply omit the ^ if you want anywhere in the string. However, in Javascript in this case you should simply use:
myString.charAt(0) === 'E' // for the beginning or
myString.indexOf('E') !== -1 // for anywhere
A regex for this simple operation is overkill.
I'm trying to check if a string contains specific letters like E or F
Regex should be:
/[EF]/.test('E22');
Your regex ^F? makes F as optional which will always return true for any input.
UPDATE: This should work without optional anchor ?
//Case1
if (/^E/.test(stringContainsE)) ....
//Case2
if (/^F/.test(stringContainsF)) ....

Matching special characters and letters in regex

I am trying to validate a string, that should contain letters numbers and special characters &-._ only. For that I tried with a regular expression.
var pattern = /[a-zA-Z0-9&_\.-]/
var qry = 'abc&*';
if(qry.match(pattern)) {
alert('valid');
}
else{
alert('invalid');
}
While using the above code, the string abc&* is valid. But my requirement is to show this invalid. ie Whenever a character other than a letter, a number or special characters &-._ comes, the string should evaluate as invalid. How can I do that with a regex?
Add them to the allowed characters, but you'll need to escape some of them, such as -]/\
var pattern = /^[a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/
That way you can remove any individual character you want to disallow.
Also, you want to include the start and end of string placemarkers ^ and $
Update:
As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._
/^[\w&.\-]+$/
[\w] is the same as [a-zA-Z0-9_]
Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead:
/^[\w&.\-]*$/
Well, why not just add them to your existing character class?
var pattern = /[a-zA-Z0-9&._-]/
If you need to check whether a string consists of nothing but those characters you have to anchor the expression as well:
var pattern = /^[a-zA-Z0-9&._-]+$/
The added ^ and $ match the beginning and end of the string respectively.
Testing for letters, numbers or underscore can be done with \w which shortens your expression:
var pattern = /^[\w&.-]+$/
As mentioned in the comment from Nathan, if you're not using the results from .match() (it returns an array with what has been matched), it's better to use RegExp.test() which returns a simple boolean:
if (pattern.test(qry)) {
// qry is non-empty and only contains letters, numbers or special characters.
}
Update 2
In case I have misread the question, the below will check if all three separate conditions are met.
if (/[a-zA-Z]/.test(qry) && /[0-9]/.test(qry) && /[&._-]/.test(qry)) {
// qry contains at least one letter, one number and one special character
}
Try this regex:
/^[\w&.-]+$/
Also you can use test.
if ( pattern.test( qry ) ) {
// valid
}
let pattern = /^(?=.*[0-9])(?=.*[!##$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!##$%^&*]{6,16}$/;
//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format
let reee =pattern .test("helLo123#"); //true as it contains all the above
I tried a bunch of these but none of them worked for all of my tests. So I found this:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$
from this source: https://www.w3resource.com/javascript/form/password-validation.php
Try this RegEx: Matching special charecters which we use in paragraphs and alphabets
Javascript : /^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$/.test(str)
.test(str) returns boolean value if matched true and not matched false
c# : ^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$
Here you can match with special char:
function containsSpecialChars(str) {
const specialChars = /[`!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
return specialChars.test(str);
}
console.log(containsSpecialChars('hello!')); // 👉️ true
console.log(containsSpecialChars('abc')); // 👉️ false
console.log(containsSpecialChars('one two')); // 👉️ false

Regular Expression - followed by

How can I write a regex that match this
123/456
123/456/?
but not this
123/456/
I want on the second / it must be followed by a ?.
For Example I would like it to match this
'123/456'.match(X) // return ['123/456']
'123/456/?'.match(X) // return ['123/456/?']
'123/456/'.match(X) // return null
Update
I missed to say one important thing. It must not end with '?', a string like '123/456/?hi' should also match
You can try this regex: \d{3}/\d{3}(/\?.*)?
It will match
3 digits
followed by a /
followed by 3 digits
followed by /?any_text (e.g. /?hi) (optional)
This example uses regular expression anchors like ^ and $, but they are not required if you only try to match against the target string.
var result = '123/456/?hi'.match(/\d{3}\/\d{3}(\/\?.*)?/);
if (result) {
document.write(result[0]);
}
else {
document.write('no match');
}
This regular expression will work /^\d{3}\/\d{3}(\/\?.*)?/
See this JSFiddle.
Note: if you think it should match any number of digits then use \d+ instead of \d{3}. The later matches exactly 3 digits.
Here you are:
[0-9]+/[0-9]+(/\?[^ ]*)?
What other rules do you have?
If you want to accept all strings with last character other than ?, use "[^?]$"
If you want to accept strings that start with 123/456 and optionally end with /?, use "^123/456(/\?)?$"
I think this should work:
'123/456'.match(/^123\/456(\/\?)?$/) // returns ["123/456", undefined]
'123/456/'.match(/^123\/456(\/\?)?$/) // returns null
'123/456/?'.match(/^123\/456(\/\?)?$/) // returns ["123/456/?", "/?"]
EDIT: added the other cases

Categories