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

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

Related

Why does't regex match all numbers instead of numbers just at the end of the string?

I was just looking for a regex that would watch the last numerical (\d or [0-9]) in a given string , strings like:
var str = "7-Dec-1985"
var str = "#scrollto-section-4"
Of-course I found an answer in the following thread on SO HERE
I am using a regex like the following:
str.match(/\d+$/)
Works fine, no issues, now I used the following tool to analysis the regex HERE,
\d+ //matches greedy 0 to as many
$ - specifies that the search should start at the end of the string
But why does that above regex in the below example:
var str = "7-Dec-1985"
Match only 1985 why not 71985 ?
Because $ means "end of input" (or "end of line or end of input" if you specify the m flag), and \d+ means a contiguous series of digits (not digits mixed with other things). So \d+$ means "a contiguous series of digits right before the end."
If you want to match anywhere, remove the $. Additionally, if you want to match more than once, you'll need a g ("global") flag on it.
Examples -- your original:
var str = "7-Dec-1985";
document.body.innerHTML = JSON.stringify(str.match(/\d+$/));
Without the $, but no g:
var str = "7-Dec-1985";
document.body.innerHTML = JSON.stringify(str.match(/\d+/));
Without the $ and with g:
var str = "7-Dec-1985";
document.body.innerHTML = JSON.stringify(str.match(/\d+/g));
Sorry, but $ doesn't means start search at end of string.
Your regex \d+$ means match the number at end of string.
To match any number use \d+ like this.
Because there is -Dec- between 7 and 1985 which isn't digit. Also $ means end of line. So Your pattern just matches that number which is end of string (continuously).

Why does this regular expression evaluate to false in javascript?

I'm looking for a string that is 0-9 digits, no other characters.
This is alerting me with a "false" value:
var regex = new RegExp('^[\d]{0,9}$');
alert(regex.test('123456789'));
These return true, and I understand why (The ^ and $ indicate that the whole string needs to match, not just a match within the string) :
var regex = new RegExp('[\d]{0,9}');
alert(regex.test('123456789'));
-
var regex = new RegExp('[\d]{0,9}');
alert(regex.test('12345678934341243124'));
and this returns true:
var regex = new RegExp('^[\d]{0,9}');
alert(regex.test('123456789'));
So why, when I add the "$" at the end would this possibly be failing?
And what do I need to do to fix it?
When you use
var regex = new RegExp('^[\d]{0,9}$');
syntax, you'll get regex as
/^[d]{0,9}$/
Note the \d is turned into d.
This regex /^[d]{0,9}$/ will match only the d zero to nine times.
RegExp uses string to define regex, the \ is also used as escape symbol in the string, so \ in \d is considered as the escape character.
Escape the \ by preceding it with another \.
var regex = new RegExp('^[\\d]{0,9}$');
I'll recommend you to use regex literal syntax rather than the confusing RegExp syntax.
var regex = /^\d{0,9}$/;
EDIT:
The reason you get true when using var regex = new RegExp('^[\d]{0,9}'); is because the regex implies that the string should start with any number of d include zero to nine. So, event when the string does not starts with d the condition is stratified because of 0 as the minimum no of occurrences.
You might want to check if the string starts with one to nine digits.
var regex = /^\d{1,9}$/;
You should use the regular expression literal (without quotes and using the beginning and ending slashes) when defining the RegExp object. This is the recommended approach when the regular expression will remain constant, meaning it does not need to be compiled every time it is used. This gives you the desired result:
var regex = new RegExp(/^[\d]{0,9}$/);
Because $ means End of line, and your string does not have an end of line as last character
May be you are looking for "\z"

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

Regex match Array words with dash

I want to match some keywords in the url
var parentURL = document.referrer;
var greenPictures = /redwoods-are-big.jpg|greendwoods-are-small.jpg/;
var existsGreen = greenPictures.test(parentURL);
var existsGreen turns true when it finds greendwoods-are-small.jpg but also when it finds small.jpg
What can i do that it only turns true if there is exactly greendwoods-are-small.jpg?
You can use ^ to match the beginning of a string and $ to match the end:
var greenPictures = /^(redwoods-are-big.jpg|greendwoods-are-small.jpg)$/;
var existsGreen = greenPictures.test(parentURL);
But of cause the document.referrer is not equal ether redwoods-are-big.jpg or greendwoods-are-small.jpg so i would match /something.png[END]:
var greenPictures = /\/(redwoods-are-big\.jpg|greendwoods-are-small\.jpg)$/; // <-- See how I escaped the / and the . there? (\/ and \.)
var existsGreen = greenPictures.test(parentURL);
Try this regex:
/(redwoods-are-big|greendwoods-are-small)\.jpg/i
I used the i flag for ignoring the character cases in parentURL variable.
Description
Demo
http://regex101.com/r/aI4yJ6
Dashes does not have any special meaning outside character sets, e.g.:
[a-f], [^x-z] etc.
The characters with special meaning in your regexp is | and .
/redwoods-are-big.jpg|greendwoods-are-small.jpg/
| denotes either or.
. matches any character except the newline characters \n \r \u2028 or \u2029.
In other words: There is something else iffy going on in your code.
More on RegExp.
Pages like these can be rather helpful if you struggle with writing regexp's:
regex101 (with sample)
RegexPlanet
RegExr
Debuggex
etc.

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

Categories

Resources