JS - Regex for one letter and 6 numbers - javascript

I have this regular expression to test if an input starts with the letter "a" and is followed by 6 numbers. On the online validator seems to work, but on JavaScript doesnt.
This is the code:
function checkBookingReference (ref) {
var regex = /(^a|A)([0-9]{6})/;
return regex.test(ref);
}
The function returns true if I enter more than six numbers, and it shouldn't. Any idea why?

That regex will return true if anywhere in the string there is a match. If you want to ensure the entire string matches it, then you'll want to use ^ to match the beginning and $ to match the end.
/^(a|A)([0-9]{6})$/

This is how I would do it:
return /^A[0-9]{6}$/i.test(ref);

Use the regex object to specify the regular expression and then test it. Try this
var regex = new RegExp("^a([0-9]{6})$","i");
return regex.test(ref);

You nee to move the carat ^ outside the parentheses and use a proper group around the letters, then loose the trailing dollar sign $. Try this:
var regex = /^[aA][0-9]{6}/;
The parenthesis inside meant "not". Outside it means "beginning of string". The dollar sign meant "end of string".

Related

check every occurrence of a special character followed by a whitespace using regex

I'm trying to check for every occurrence that a string has an # at the beginning of a string.
So something like this works for only one string occurance
const comment = "#barnowl is cool"
const regex = /#[a-z]/i;
if (comment.charAt(0).includes("#")) {
if (regex.test(comment)) {
// do something
console.log('test passeed')
} else {
// do something else
}
} else {
// do other
}
but....
What if you have a textarea and a user uses the # multiple times to reference another user this test will no longer work because charAt(0) is looking for the first character in a string.
What regex test is doable in a situation where you have to check the occurrence of a # followed by a space. I know i can ditch charAt(0) and use comment.includes("#") but i want to use a regex pattern to check if there is space after wards
So if user does #username followed by a space after words, the regex should pass.
Doing this \s doesn't seem to make the test pass
const regex = /#[a-z]\s/i; // shouldn't this check for white space after a letter ?
demo:
https://jsbin.com/riraluxape/edit?js,console
I think your expression is very close. There are two things that are missing:
The [a-z] match is only looking for one character, so in order to look for multiple characters it needs to be [a-z]+.
The flags section is missing the g modifier, which enables the expression to look through the entire text string instead of just the first match.
I believe the regular expression declaration should be adjusted to the following:
const regex = /#[a-z]+\s/ig;
Is this what you want? Matching all the occurrences of the mention?
const regex = /#\w+/ig
I used the \w flag here which matches any word character.
To check for multiple matches instead of only the first one, append g to the regex:
const regex = /#[a-z]*\s/ig;
Your regex with \s actually works, see: https://regex101.com/r/gyMyvB/1

Match the same start and end character of a string with Regex

I'm trying to match the start and end character of a string to be the same vowel. My regex is working in most scenarios, but failing in others:
var re = /([aeiou]).*\1/;
re.test(str);
Sample input:
abcde, output - false (Valid)
abcda, output - true (Valid)
aabcdaa, output - true (Valid)
aeqwae, output - true (Not valid)
ouqweru, output - true (Not valid)
You need to add anchors to your string.
When you have, for example:
aeqwae
You say the output is true, but it's not valid because a is not the same as e. Well, regex simply matches the previous character (before e), which is a. Thus, the match is valid. So, you get this:
[aeqwa]e
The string enclosed in the brackets is the actual match and why it returns true.
If you change your regex to this:
/^([aeiou]).*\1$/
By adding ^, you tell it that the start of the match must be the start of the string and by adding $ you tell it that the end of the match must be the end of the string. This way, if there's a match, the whole string must be matched, meaning that aeqwae will no longer get matched.
A great tool for testing regex is Regex101. Give it a try!
Note: Depending on your input, you might need to set the global (g) or multi-line (m) flag. The global flag prevents regex from returning after the first match. The multi-line flag makes ^ and $ match the start and end of the line (not the string). I used both of them when testing with your input.
Just a different version of #Hristiyan Dodov answer that I have written for fun.
regex = /^(a|e|i|o|u).*\1$/
const strings = ['abcde', 'abcda', 'aabcdaa', 'aeqwae', 'ouqweru']
strings.forEach((e)=>{
const result = regex.test(e)
console.log(e, result)
})
Correct answer is already mentioned above, just for some more clarification:
regEx= /^([a,e,i,o,u])(.*)\1$/
Here, \1 is the backreference to match the same text again, you can reuse the same backreference more than once. Most regex flavors support up to 99 capturing groups and double-digit backreferences. So \99 is a valid backreference if your regex has 99 capturing groups.visit_for_detail
/^([aeiou])[a-z]\1$/
just a bit of improvement, to catch alphabet letters.

javascript regex to return letters only

My string can be something like A01, B02, C03, possibly AA18 in the future as well. I thought I could use a regex to get just the letters and work on my regex since I haven't done much with it. I wrote this function:
function rowOffset(sequence) {
console.log(sequence);
var matches = /^[a-zA-Z]+$/.exec(sequence);
console.log(matches);
var letter = matches[0].toUpperCase();
return letter;
}
var x = "A01";
console.log(rowOffset(x));
My matches continue to be null. Am I doing this correctly? Looking at this post, I thought the regex was correct: Regular expression for only characters a-z, A-Z
You can use String#replace to remove all non letters from input string:
var r = 'AA18'.replace(/[^a-zA-Z]+/g, '');
//=> "AA"
Your main issue is the use of the ^ and $ characters in the regex pattern. ^ indicates the beginning of the string and $ indicates the end, so you pattern is looking for a string that is ONLY a group of one or more letters, from the beginning to the end of the string.
Additionally, if you want to get each individual instance of the letters, you want to include the "global" indicator (g) at the end of your regex pattern: /[a-zA-Z]+/g. Leaving that out means that it will only find the first instance of the pattern and then stop searching . . . adding it will match all instances.
Those two updates should get you going.
EDIT:
Also, you may want to use match() rather than exec(). If you have a string of multiple values (e.g., "A01, B02, C03, AA18"), match() will return them all in an array, whereas, exec() will only match the first one. If it is only ever one value, then exec() will be fine (and you also wouldn't need the "global" flag).
If you want to use match(), you need to change your code order just a bit to:
var matches = sequence.match(/[a-zA-Z]+/g);
To return an array of separate letters remove +:
var matches = sequence.match(/[a-zA-Z]/g);
You're confused about what the goal of the other question was: he wanted to check that there were only letters in his string.
You need to remove the anchors ^$, who match respectively the beginning and end of the string:
[a-zA-Z]+
This will match the first of letters in your input string.
If there might be more (ie you want multiple matches in your single string), use
sequence.match(/[a-zA-Z]+/g)
This /[^a-z]/g solves the problem. Look at the example below.
function pangram(str) {
let regExp = /[^a-z]/g;
let letters = str.toLowerCase().replace(regExp, '');
document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2## %hfr efg uor7 489(*&^% knt lhtkjj ngnm!##$%^&*()_');
<h4 id="letters"></h4>
You can do this:
var r = 'AA18'.replace(/[\W\d_]/g, ''); // AA
Also can be done by String.prototype.split(regex).
'AA12BB34'.split(/(\d+)/); // ["AA", "12", "BB", "34", ""]
'AA12BB34'.split(/(\d+)/)[0]; // "AA"
Here regex divides the giving string by digits (\d+)

Regular expression giving incorrect output

I am using regex to verify that a string only contains alphabets and spaces. Regex is defined as
var regex = /^[A-Za-z ]/;
but even if I am testing it with a string "X," , it is giving a true result.
What is the error here?
^[A-Za-z ] only matches one character. and ^ means the start of the string. To accomplish what you want, use:
+ - This means match one or more. Alternatively you can use:
* - Which means match zero or more.
But I think you're better off with the first one (+). Another thing is, match for the whole string. This means you have to search from the first to the last character.
$ - This means match the end.
Your code should be like this:
var regex = /^[A-Za-z ]+$/;
Your regex matches the first letter of your input and therefore true is returned.. You need to add $ to make sure you only match a complete string from the beginning (^) to the end ($).
var regex = /^[A-Za-z ]*$/;
Try using this:
/^[a-zA-Z\ ]+$/
This is the correct way:
/^[A-Za-z ]*$/
Regex Demo

Beginner JavaScript variables

It's my first time using Java Script....
What does this do?
var INTEGER_SINGLE = /\d+/;
What does the forward slashes tell you? How about the backslash? d means for digit?
Thanks!
That creates a regular expression that matches one or more digits.
Anything inside / / is a regular expression. \d matches a digit, and + is the positive closure, which means one or more.
Having said that, depending on what this regex is supposed to do, you may want to change it to:
var INTEGER_SINGLE = /^\d+$/;
^ matches the beginning of the string, and $ the end. The end result would be that any strings you try to match against the regex would have to satisfy it in the string's entirety.
var INTEGER_SINGLE = /^\d+$/;
console.log(INTEGER_SINGLE.test(12)); //true
console.log(INTEGER_SINGLE.test(12.5)); //false
Of course if the regex is supposed to only match a single integer anywhere in the string, then of course it's perfect just the way it is.

Categories

Resources