regex custom lenght but no whitespace allowed [duplicate] - javascript

I have a username field in my form. I want to not allow spaces anywhere in the string. I have used this regex:
var regexp = /^\S/;
This works for me if there are spaces between the characters. That is if username is ABC DEF. It doesn't work if a space is in the beginning, e.g. <space><space>ABC. What should the regex be?

While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces

Use + plus sign (Match one or more of the previous items),
var regexp = /^\S+$/

If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex #Bergi mentioned just the string version for new RegExp constructor

This will help to find the spaces in the beginning, middle and ending:
var regexp = /\s/g

This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.
/^([A-z0-9!##$%^&*().,<>{}[\]<>?_=+\-|;:\'\"\/])*[^\s]\1*$/
Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.
If you want just alphanumeric characters then change what is in the [] like so:
/^([A-z])*[^\s]\1*$/

Related

Not sure why this Regex is returning true

Trying to use this regex to verify usernames and this is what I have :
var goodUsername = /[a-zA-Z0-9_]/g;
console.log(goodUsername.test("HELO $"));
But wether or not I have $ in there it returns true. Not sure why.
I basically only want letters, numbers and _ in usernames and that's it
It seems to work here https://regex101.com/r/nP4iG7/1
The RegEx that you use searches any match in the subject string. In your case HELO matches the criteria. If you like to apply the criteria to the whole string you should define the string begin and end using
var goodUsername = /^[a-zA-Z0-9_]+$/;
console.log(goodUsername.test("HELO $"));//false
You need to add anchors..
/^[a-zA-Z0-9_]+$/;
Anchors help to do exact matching. ^ start of the line anchor, $ end of the line anchor. And also you need to repeat the char class one or more times otherwise it would match a string which contains exactly one character.
You could search for any characters not in the list (a "negated character set"):
var badUsername = /[^a-zA-Z0-9_]/;
console.log(!badUsername.test("HELO $"));
or more simply
var badUsername = /\W/;
since \W is defined as
Matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_].
If you prefer to do a positive match, using anchors as other answers have suggested, you can shorten your regexp by using \w:
var goodUsername = /^\w+$/;

Regular expression for validating with specific characters through javascript

I want to validate a string that does not allows the following characters.
<,>,:,","/,\,|,?,*,#
I want to validate this through JavaScript.
I was trying this with the following code.
var reg = /[^a-zA-Z0-9 \-_]+/;
reg.test(filename[0])
But this was unable to validating the symbol #.
Please help.
The problem you have is that you included the hyphen in the middle of the pattern without escaping it. This tells the engine that you are expecting a range--in this case space through underscore. It's easier (in my opinion) to place the hyphen as either the first or last character in the pattern, at which point you don't have to escape it. (It would be the second character if you are using a negated character class.)
e.g.
var reg = /[^a-zA-Z0-9 \-_]+/;
--OR--
var reg = /[^a-zA-Z0-9 _-]+/;
--OR--
var reg = /[^-a-zA-Z0-9 _]+/;
Do you only want to allow English letters a-z (and A-Z), numbers, the space, '_', and '-'? If so, that is different than disallowing the characters you specified since '☃' doesn't have the characters you provided but may not be a valid string in your use case.
In the case you just want the English alphabet, numbers, space, '_', and '-', you can use the following RegExp and conditional:
var reg = /^[a-zA-Z0-9 \-_]+$/;
if (reg.test(filename[0])) {
// String is ok
}
This says everything in the string between beginning (^) and end ($) must be one or more of the allowed characters.
If you want to disallow the characters you provided in your question, you can use:
var reg = /[\<\>\:\,\/\\\|\?\*\#]/;
if (!reg.test(filename[0])) {
// String is ok
}
This says to search for any of the characters you've listed (they are all escaped with a \ before them) and if you find any, the string is invalid. So only if the test fails is the string a valid string - that's why there's a ! before the test.
string sourceString ="something" ;
var outString = sourceString.replace(/[`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');

regexp problem, the dot selects all text

I use some jquery to highlight search results. For some reason if i enter a basis dot, all of the text get selected. I use regex and replace to wrap the results in a tag to give the found matches a color.
the code that i use
var pattern = new.RegExp('('+$.unique(text.split(" ")).join("|")+")","gi");
how can i prevent that the dot selects all text, so i want to leave the point out of the code(the dot has no power)
You may be able to get there by doing this:
var pattern = new.RegExp('('+$.unique(text.replace('.', '\\.').split(" ")).join("|")+")","gi");
The idea here is that you're attempting to escape the period, which acts as a wild card in regex.
This will replace all special RegExp characters (except for | since you're using that to join the terms) with their escaped version so you won't get unwanted matches or syntax errors:
var str = $.unique(text.split(" ")).join("|"),
pattern;
str = str.replace(/[\\\.\+\*\?\^\$\[\]\(\)\{\}\/\'\#\:\!\=]/ig, "\\$&");
pattern = new RegExp('('+str+')', 'gi');
The dot is supposed to match all text (almost everything, really). If you want to match a period, you can just escape it as \..
If you have a period in your RegExp it's supposed to match any character besides newline characters. If you don't want that functionality you need to escape the period.
Example RegExp with period escaped /word\./
You need to escape the text you're putting into the regex, so that special characters don't have unwanted meanings. My code is based on some from phpjs.org:
var words = $.unique(text.split(" ")).join("|");
words = words.replace(/[.\\+*?\[\^\]$(){}=!<>|:\\-]/h, '\\$&'); // escape regex special chars
var pattern = new RegExp('(' + words + ")","gi");
This escapes the following characters: .\+*?[^]$(){}=!<>|:- with a backslash \ so you can safely insert them into your new RegExp construction.

Regex from character until end of string

Hey. First question here, probably extremely lame, but I totally suck in regular expressions :(
I want to extract the text from a series of strings that always have only alphabetic characters before and after a hyphen:
string = "some-text"
I need to generate separate strings that include the text before AND after the hyphen. So for the example above I would need string1 = "some" and string2 = "text"
I found this and it works for the text before the hyphen, now I only need the regex for the one after the hyphen.
Thanks.
You don't need regex for that, you can just split it instead.
var myString = "some-text";
var splitWords = myString.split("-");
splitWords[0] would then be "some", and splitWords[1] will be "text".
If you actually have to use regex for whatever reason though - the $ character marks the end of a string in regex, so -(.*)$ is a regex that will match everything after the first hyphen it finds till the end of the string. That could actually be simplified that to just -(.*) too, as the .* will match till the end of the string anyway.

Javascript split regex question

hello I am trying what I thought would be a rather easy regex in Javascript but is giving me lots of trouble.
I want the ability to split a date via javascript splitting either by a '-','.','/' and ' '.
var date = "02-25-2010";
var myregexp2 = new RegExp("-.");
dateArray = date.split(myregexp2);
What is the correct regex for this any and all help would be great.
You need the put the characters you wish to split on in a character class, which tells the regular expression engine "any of these characters is a match". For your purposes, this would look like:
date.split(/[.,\/ -]/)
Although dashes have special meaning in character classes as a range specifier (ie [a-z] means the same as [abcdefghijklmnopqrstuvwxyz]), if you put it as the last thing in the class it is taken to mean a literal dash and does not need to be escaped.
To explain why your pattern didn't work, /-./ tells the regular expression engine to match a literal dash character followed by any character (dots are wildcard characters in regular expressions). With "02-25-2010", it would split each time "-2" is encountered, because the dash matches and the dot matches "2".
or just (anything but numbers):
date.split(/\D/);
you could just use
date.split(/-/);
or
date.split('-');
Say your string is:
let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;
You want to split the string by the following delimiters:
Colon
Semicolon
New line
You could split the string like this:
let rawElements = str.split(new RegExp('[,;\n]', 'g'));
Finally, you may need to trim the elements in the array:
let elements = rawElements.map(element => element.trim());
Then split it on anything but numbers:
date.split(/[^0-9]/);
or just use for date strings 2015-05-20 or 2015.05.20
date.split(/\.|-/);
try this instead
date.split(/\W+/)

Categories

Resources