Select 4 last digits in any string - javascript

I'm having an array of various string and I need to select from each of the strings last 4 digits that are not separated.
var example = ["eg3322-3748", "eg3322-3749_ABCD", "eg3750_5GHJ"];
The desired result should give these results:
var example = ["3748", "3749", "3750"]
Thanks! :)

This should do it:
const input = ['eg3322-3748', 'eg3322-3749_ABCD', 'eg3750_5GHJ'];
const result = input.map(item =>
item
.split('').reverse().join('') // Reverse string
.match(/\d{4}/)[0] // Find first 4 consecutive digits
.split('').reverse().join('') // Reverse matches back
);
console.log(result);
PS: next time you ask a question, please show what you attempted. Thanks!
Edit: this will generate an error if any string does not contain 4 consecutive digits. You can easily fix that by adding a fallback to match (with [''], for instance, then it'll return that).

Logic:
Based on given data, its obvious, you are looking for a batch of alphanumeric/numeric characters and wish to get last 4 digits.
So you can create a regex that matches all such groups, and returns last one.
Then, from this last group, just extract last 4 characters and Ta-da!!!
var example = ["eg3322-3748", "eg3322-3749_ABCD", "eg3750_5GHJ"];
var regex = /([a-z]*\d{4,})/g;
var output = example.map((str) => {
const match = str.match(regex).pop();
return match.substr(-4);
});
console.log(output)

You can use .substr() function to slice the length of string. Maybe "example(i).substr(example(i).length - 4)" will work.

Related

Regular expression for remove everything except 10 number?

I learn right now regular expression and need to know, how I can remove all except 10 numbers or maximum 10 number, I tried to create RegExp like this
var value = value.replace(/[^\d]/g, '')
You can use regex's {0,10} range of times to specify the length of the number.
My example will produce to matches,
[
"1348737734",
"8775"
]
It will match first number with the length of 10, and the rest of the number.
const str = 'asb13487377348775nvnn';
const result = str.match(/(\d{1,10})/g);
console.log(result);

Regex replace for preceding zero twice in string with different condition

I have string XY4PQ43 and I want regex replace should output XY04PQ0043 in JavaScript. For first number in a string I want zero prefix if its single digit to make it 2 digits and for second number in string I want prefix zeros if its less than 4 digit number. Below output expected for regex.
AB1CD123 => AB01CD0123
MN12XYZ1 => MN12XY0001
LJ99P1234 => IJ99P1234
Any jsfiddle or codepen example preferred
Try this.
function format(text) {
let match = /^(.*?)(\d+)(.*?)(\d+)$/.exec(text);
return [
match[1],
match[2].padStart(2, '0'),
match[3],
match[4].padStart(4, '0'),
].join('');
}
console.log(format('AB1CD123'));
console.log(format('MN12XYZ1'));
console.log(format('LJ99P1234'));
For that given string, you can apply the following regex:
var _str = 'AB1CD123';
_str.match(new RegExp(/([A-Z]{2})([0-9]{1,2})([A-Z]{2})([0-9]{1,4})/))
It outputs an array with values matched starting from 1 to 4, where 2 and 4 are the ones you need to manage. For those values you can apply logic - add leading zeros - by checking their length and merge them afterwards. Try it in browser console.
Note: it works for this specific example. For other examples you need to adjust the length matched.

Best way to manipulate and cut a string using character matching?

So in my example, we have strings that look like this:
CP1_ctl05_RCBPAThursdayStartTimePicker_0_dateInput
CP1_ctl05_RCBPAFridayStartTimePicker_3_dateInput
CP1_ctl05_RCBPAMondayStartTimePicker_1_dateInput
The task is to extract the days of the week from the string.
I already figured you can trim the first set of characters CP1_ctl05_RCBPA as they will always have the same length and will always occur in the same position. Using string.substr(15), I was able to reduce the string to FridayStartTimePicker_3_dateInput but I am not sure how to approach deleting the rest of the suffixal garbage text.
I was thinking about trimming the end by finding the first occurring y (as it will only occur in days of the week in this case) and slicing off the end up until that point, but I am not sure about how to approach slicing off a part of a string like this.
You can use regex to extract them. As every day ends with a y, and no day has a y in between, you can simply use that as delimiter
const regex = /\w{15}(\w+y).*/g;
const str = `CP1_ctl05_RCBPAThursdayStartTimePicker_0_dateInput`;
const subst = `\$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Instead of deleting unwanted parts, you could just match what you want.
The following regex ^.{15}(\w+?y) matches 15 any character from the begining of the string then matches and capture in group 1 one or more word character not greedy then the letter y. It is mandatory to use not greedy ? unless it will match until the last y that exists in the string.
We then just have to get the content of the first group and assign to variable day
var test = [
'CP1_ctl05_RCBPAThursdayStartTimePicker_0_dateInput', 'CP1_ctl05_RCBPAFridayStartTimePicker_3_dateInput', 'CP1_ctl05_RCBPAMondayStartTimePicker_1_dateInput'
];
console.log(test.map(function (a) {
return a.match(/^.{15}(\w+?y)/)[1]
}));

javascript getting a faulty result using a regular expression

In my web page, I have:
var res = number.match(/[0-9\+\-\(\)\s]+/g);
alert(res);
As you can see, I want to get only numbers, the characters +, -, (, ) and the space(\s)
When I tried number = '98+66-97fffg9', the expected result is: 98+66-979
but I get 98+66-97,9
the comma is an odd character here! How can eliminate it?
Its probably because you get two groups that satisfied your expression.
In other words: match mechanism stops aggregating group when it finds first unwanted character -f. Then it skips matching until next proper group that, in this case, contains only one number - 9. This two groups are separated by comma.
Try this:
var number = '98+66-97fffg9';
var res = number.match(/[0-9\+\-\(\)\s]+/g);
// res is an array! You have to join elements!
var joined = res.join('');
alert(joined);
You're getting this because your regex matched two results in the number string, not one. Try printing res, you'll see that you've matched both 98+66-979 as well as 9
String.match returns an array of matched items. In your case you have received two items ['98+66-97','9'], but alert function outputs them as one string '98+66-97,9'. Instead of match function use String.replace function to remove(filter) all unallowable characters from input number:
var number = '98+66-97fffg9',
res = number.replace(/[^0-9\+\-\(\)\s]+/g, "");
console.log(res); // 98+66-979
stringvariable.match(/[0-9\+\-\(\)\s]+/g); will give you output of matching strings from stringvariable excluding unmatching characters.
In your case your string is 98+66-97fffg9 so as per the regular expression it will eliminate "fffg" and will give you array of ["98+66-97","9"].
Its default behavior of match function.
You can simply do res.join('') to get the required output.
Hope it helps you
As per documents from docs, the return value is
An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.
S,your return value contains
["98+66-97", "9"]
So if you want to skip parentheses-captured matched results
just remove g flag from regular expression.
So,your expression should like this one
number.match(/[0-9\+\-\(\)\s]+/); which gives result ["98+66-97"]

Whats wrong with this regex logic

I am trying to fetch the value after equal sign, its works but i am getting duplicated values , any idea whats wrong here?
// Regex for finding a word after "=" sign
var myregexpNew = /=(\S*)/g;
// Regex for finding a word before "=" sign
var mytype = /(\S*)=/g;
//Setting data from Grid Column
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
var newtype = mytype.exec(strNew);
alert(matchNew);
https://jsfiddle.net/6vjjv0hv/
exec returns an array, the first element is the global match, the following ones are the submatches, that's why you get ["=20", "20"] (using console.log here instead of alert would make it clearer what you get).
When looking for submatches and using exec, you're usually interested in the elements starting at index 1.
Regarding the whole parsing, it's obvious there are better solution, like using only one regex with two submatches, but it depends on the real goal.
You can try without using Regex like this:
var val = 'QCById=20';
var myString = val.substr(val.indexOf("=") + 1);
alert(myString);
Presently exec is returning you the matched value.
REGEXP.exec(SOMETHING) returns an array (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec).
The first item in the array is the full match and the rest matches the parenthesized substrings.
You do not get duplicated values, you just get an array of a matched value and the captured text #1.
See RegExp#exec() help:
If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.
Just use the [1] index to get the captured text only.
var myregexpNew = /=(\S*)/g;
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
if (matchNew) {
console.log(matchNew[1]);
}
To get values on both sides of =, you can use /(\S*)=(\S*)/g regex:
var myregexpNew = /(\S*)=(\S*)/g;
var strNew = "QCById=20";
var matchNew = myregexpNew.exec(strNew);
if (matchNew) {
console.log(matchNew[1]);
console.log(matchNew[2]);
}
Also, you may want to add a check to see if the captured values are not undefined/empty since \S* may capture an empty string. OR use /(\S+)=(\S+)/g regex that requires at least one non-whitespace character to appear before and after the = sign.

Categories