Using regular expression in Javascript - javascript

I need to check whether information entered are 3 character long, first one should be 0-9 second A-Z and third 0-9 again.
I have written pattern as below:
var pattern = `'^[A-Z]+[0-9]+[A-Z]$'`;
var valid = str.match(pattern);
I got confused with usage of regex for selecting, matching and replacing.
In this case, does[A-Z] check only one character or whole string ?
Does + separate(split?) out characters?

1) + matches one or more. You want exactly one
2) declare your pattern as a REGEX literal, inside forward slashes
With these two points in mind, your pattern should be
/^[A-Z][0-9][A-Z]$/
Note also you can make the pattern slightly shorter by replacing [0-9] with the \d shortcut (matches any numerical character).
3) Optionally, add the case-insensitive i flag after the final trailing slash if you want to allow either case.
4) If you want to merely test a string matches a pattern, rather than retrieve a match from it, use test(), not match() - it's more efficient.
var valid = pattern.test(str); //true or false

+ means one or more characters so a possible String would be ABCD1234EF or A3B, invalid is 3B or A 6B

This is the regex you need :
^[0-9][A-Z][0-9]$
In this case, does[A-Z] check only one character or whole string ?
It's just check 1 char but a char can be many times in a string..
you should add ^ and $ in order to match the whole string like I did.
Does + separate(split?) out characters?
no.
+ sign just shows that a chars can repeat 1+ times.

"+" means one or more. In your case you should use exact quantity match:
/^\w{1}\d{1}\w{1}$/

Related

regex replace certain character but not for particular set in javascript

var str='select * from where item1=abcd and price>=20';
I am using the below code to replace the '=' to empty space
str=str.replace(/[=]/g, " ")
but it is also replacing '>=' . I want >= not to be replaced with any thing and also for some others condition like '==' or '<=' etc.
So my output should be - 'select * from where item abcd and price>=20'
Please help me to achieve this.
Use below regex for replacement
/([a-z0-9]+)\s*=\s*([a-z0-9]+)/gi
and replace it with $1 $2.
([a-z0-9]+): Match one or more alphanumeric characters and add them to capturing group
\s*: Zero or more space characters
=: Equal sign
gi: g: Global flag to match all possible matches. i: Case-insensitive flag.
$n in the replacement part is the nth captured group value.
var regex = /([a-z0-9]+)\s*=\s*([a-z0-9]+)/gi;
var str = 'select * from where item1=abcd and price>=20';
console.log(str.replace(regex, '$1 $2'));
Replace an equal sign with a letter or number on either side with the corresponding characters around a space.
str.replace(/([a-zA-Z0-9])=([a-zA-Z0-9])/, '$1 $2')
In regex [] means "the set of", so [a-zA-Z0-9] is one character from the set of any lowercase, uppercase, or digit.
Simple and dirty trick. Remove g from regx
var str='select * from where item1=abcd and price>=20';
console.log(str.replace(/[=]/, " "))
A good way to approach these problems is to capture everything you wish to skip, and then not capture everything you wish you remove. In your case:
(>=|<=|==|'[^']*(?:''[^']*)*')|=
and replace with $1.
Working example: https://regex101.com/r/3pT9ib/3
First we have a capturing group: (...), which is captured into $1.
The group matched >= and <=. I also threw in == (is this valid in SQL?) and escaped SQL strings, just for the example.
If we were not able to match the group, we can safely match and remove the leftover =.
This approach is explained nicely here: Regex Pattern to Match, Excluding when... / Except between

Query on Javascript RegEx

I need a regex that allows 0-9, a-z, A-Z, hyphen, question mark and "/" slash characters alone. Also the length should be between 5 to 15 only.
I tried as follows, but it does not work:
var reg3 = /^([a-zA-Z0-9?-]){4,15}+$/;
alert(reg3.test("abcd-"));
length should be between 5 to 15 only
Is that why you have this?
{4,15}+
Just use {5,15}; it’s already a quantifier, and a + after it won’t work. Apart from that, the group isn’t necessary, but things should work.
/^[a-zA-Z0-9?/-]{5,15}$/
(I also added a slash character.)
This is what you need:
if (/^([a-z\/?-]{4,15})$/i.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
REGEX EXPLANATION
^([a-z\/?-]{4,15})$
Options: Case insensitive
Assert position at the beginning of the string «^»
Match the regex below and capture its match into backreference number 1 «([a-z\/?-]{4,15})»
Match a single character present in the list below «[a-z\/?-]{4,15}»
Between 4 and 15 times, as many times as possible, giving back as needed (greedy) «{4,15}»
A character in the range between “a” and “z” (case insensitive) «a-z»
The literal character “/” «\/»
The literal character “?” «?»
The literal character “-” «-»
Assert position at the very end of the string «$»
Couple issues,
you need {5,15} instead of {4,15}+
need to include /
Your code can be rewritten as
var reg3 = new RegExp('^[a-z0-9?/-]{5,15}$', 'i'); // i flag to eliminate need of A-Z
alert(reg3.test("a1?-A7="));
Update
Let's not confuse can be with MUST be and concentrate on the actual thing I was trying to convey.
{4,15}+ part in /^([a-zA-Z0-9?-]){4,15}+$/ should be written as {5,15}, and / must be included; which will make your regexp
/^([a-zA-Z0-9?/-]){5,15}$/
which CAN be written as
/^[a-z0-9?/-]{5,15}$/i // i flag to eliminate need of A-Z
Also I hope everybody is OK with use of /i

Regular expression to check contains only

EDIT: Thank you all for your inputs. What ever you answered was right.But I thought I didnt explain it clear enough.
I want to check the input value while typing itself.If user is entering any other character that is not in the list the entered character should be rolled back.
(I am not concerning to check once the entire input is entered).
I want to validate a date input field which should contain only characters 0-9[digits], -(hyphen) , .(dot), and /(forward slash).Date may be like 22/02/1999 or 22.02.1999 or 22-02-1999.No validation need to be done on either occurrence or position. A plain validation is enough to check whether it has any other character than the above listed chars.
[I am not good at regular expressions.]
Here is what I thought should work but not.
var reg = new RegExp('[0-9]./-');
Here is jsfiddle.
Your expression only tests whether anywhere in the string, a digit is followed by any character (. is a meta character) and /-. For example, 5x/- or 42%/-foobar would match.
Instead, you want to put all the characters into the character class and test whether every single character in the string is one of them:
var reg = /^[0-9.\/-]+$/
^ matches the start of the string
[...] matches if the character is contained in the group (i.e. any digit, ., / or -).
The / has to be escaped because it also denotes the end of a regex literal.
- between two characters describes a range of characters (between them, e.g. 0-9 or a-z). If - is at the beginning or end it has no special meaning though and is literally interpreted as hyphen.
+ is a quantifier and means "one or more if the preceding pattern". This allows us (together with the anchors) to test whether every character of the string is in the character class.
$ matches the end of the string
Alternatively, you can check whether there is any character that is not one of the allowed ones:
var reg = /[^0-9.\/-]/;
The ^ at the beginning of the character class negates it. Here we don't have to test every character of the string, because the existence of only character is different already invalidates the string.
You can use it like so:
if (reg.test(str)) { // !reg.test(str) for the first expression
// str contains an invalid character
}
Try this:
([0-9]{2}[/\-.]){2}[0-9]{4}
If you are not concerned about the validity of the date, you can easily use the regex:
^[0-9]{1,2}[./-][0-9]{1,2}[./-][0-9]{4}$
The character class [./-] allows any one of the characters within the square brackets and the quantifiers allow for either 1 or 2 digit months and dates, while only 4 digit years.
You can also group the first few groups like so:
^([0-9]{1,2}[./-]){2}[0-9]{4}$
Updated your fiddle with the first regex.

jQuery/JavaScript regex to match any three first characters followed by an exact string

I need a regular expression to validate a form, based on the value of a drop down. The value, however, is randomly generated by PHP (but is always a 2 digit number).
It needs to be valid for "38|One Evening" The number 38 is what's going to change. So far, I have
//return value of dropdown
var priceOption = $("#price_option-4").val();
//make sure it ends with "One Evening"
var oneEvening = priceOption.match(/^ * + 'One Evening' $/);
Which I thought would match any string as long as it's followed by "one evening"
strings are not to be use with regex, you should just write what you want to match\test inside the regex literal, without the quotes.
/^\d{2}\|One Evening$/.test(priceOption);
// ^^^^^^ Begins with two digits
// ^^ Escaped the | meta char.
// ^^^^^^^^^^^^ Then until the end: One Evening
Simply use
/^\d\d\|One Evening$/.test(priceOption);
For xx|One Evening
/^\d{2}\|One Evening$/
/^.+?One Evening$/
Breaking it down
// ^ starts with
// . any character
// + quantifier - one or more of preceding character
// ? non-greedy - ensure regex stops at One Evening.
// One Evening = literal text
// $ match end of string.
Note that my answer reflects the requirement to match any sequence of characters, then One Evening.
I think you may be better off being more specific and ensuring you definitely have two numeric characters.
If you can it is best to be specific. Try the following:
// <start of string> <2 digits> <|One Evening> <end of string>
/^\d{2}\|One Evening$/.test( priceOption );

Removing Numbers from a String using Javascript

How do I remove numbers from a string using Javascript?
I am not very good with regex at all but I think I can use with replace to achieve the above?
It would actually be great if there was something JQuery offered already to do this?
//Something Like this??
var string = 'All23';
string.replace('REGEX', '');
I appreciate any help on this.
\d matches any number, so you want to replace them with an empty string:
string.replace(/\d+/g, '')
I've used the + modifier here so that it will match all adjacent numbers in one go, and hence require less replacing. The g at the end is a flag which means "global" and it means that it will replace ALL matches it finds, not just the first one.
Just paste this into your address bar to try it out:
javascript:alert('abc123def456ghi'.replace(/\d+/g,''))
\d indicates a character in the range 0-9, and the + indicates one or more; so \d+ matches one or more digits. The g is necessary to indicate global matching, as opposed to quitting after the first match (the default behavior).

Categories

Resources