Regular expression giving incorrect output - javascript

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

Related

Javascript: Remove trailing chars from string if they are non-numeric

I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D
I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end.
The problem I am having is that the format is not the same for the codes.
I may have M84.534DAC, or M84.534.
What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:
M84.534D -> I need to pass M84.534
M84.534DAC -> I also need to pass M84.534
Is there any function or regex that will do that?
Thank you in advance to all.
You can use the regex below. It will remove anything from the end of the string that is not a number
let code = 'M84.534DAC'
console.log(code.replace(/[^0-9]+?$/, ""));
[^0-9] matches anything that is not a numer
+? Will match between 1 and unlimited times
$ Will match the end of the string
So linked together, it will match any non numbers at the end of the string, and replace them with nothing.
You could use the following expression:
\D*$
As in:
var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);
Explanation:
\D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.
Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.
I've used document.write just so we can see the results. You use this whatever way you want.
var testData = [
'M84.534D',
'M84.534DAC'
]
regex = /\D+$/
testData.forEach((item) => {
var cleanValue = item.replace(regex, '')
document.write(cleanValue + '<br>')
})
RegEx breakdown:
\D = Anything that's not a digit
+ = One or more occurrences
$ = End of line/input

Use Regex to Replace the Starting substring

The following statement needs to be replaced, as in the following code
page_url.replace("www.", "");
This needs to be done with the use of regex. Please let me know the method of achieving the same.
Logically, it needs to replace the "www." with "" if and only if the string starts with www..
"www.test.com".replace(/^www\./, "") // returns "test.com"
or in long form:
var regex = /^www\./;
var stringToMatch = "www.test.com";
var result = stringToMatch.replace(regex, ""); // "test.com"
where the /^www\./ defines the regex object. This is made up of:
/ start of the regex
^ start of string, means this match must appear at the begining
www match the characters www
\. match the character .. We must escape it with \ because in regex . means match anything
/ end of the regex definition
If you wan't to play about with the regex to see how it works, try it in this web regex tester: https://regex101.com/r/7ErXz8/2

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+$/;

Regex to match char/digit/digit/digit

In fiddle : http://jsfiddle.net/rtucgv74/
I'm attempting to match the first char with 3 digits. So below code should alert f234. But instead null is returned ?
src :
var reg = /^\[a-zA-Z]\d{3}/;
alert(reg.exec(("test f234 sadfas")[1]))
How do extract char/digit/digit/digit from string ?
Almost right, but the first backslash in your regex is making the [ match an actual bracket instead of defining a character set.
And the ^ is preventing it from matching anything not at the beginning of the string.
So the correct regex is /[a-zA-Z]\d{3}/ or /[a-z]\d{3}/i
The other problem is that you try to read the second element of the result array. But you're not capturing anything in your regex, so there will be only one element ([0]) which is the whole match.
Try:
reg.exec("test f234 sadfas")[0]
In your example, you are picking out a string from a "sentence", so remove the ^. Also remove the \ that escapes the [. So you want:
[a-zA-Z]\d{3}
Test it here: http://regexr.com/3bta7
Try something like this:
var reg = /[a-zA-Z]{1}[0-9]{3}/;
alert("test f234 asdfghj".match(reg))
Check the Demo fiddle
UPDATE WITH BOUNDARY SUPPORT:
The regex will match also part of words like abc12335 so to void this behaviour you could try this regex:
var reg = /\b[a-zA-Z]{1}[0-9]{3}\b/;
alert("test aaf23412 asdfghj".match(reg)) // not match
alert("test f234 asdfghj".match(reg)) // match !
alert("test f2343 asdfghj".match(reg)) // not match
Check the demo fiddle 2
The \ in your regex escapes character [ and makes it non special. And the character ^ prevents your regex to match any part that is not in the beginning of the string.
So this would work :
var reg = /[a-zA-Z]\d{3}/;
alert(reg.exec("test f234 sadfas")[0]);
Note that there is only one element in the result because your regex don't contain any capture (characters between brackets).
This can help you find the first character occurring before 3 digits:
\w(?=\d{3}).

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+)

Categories

Resources