Regular expression for remove everything except 10 number? - javascript

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

Related

How to round of prices with comma's instead of dots?

In The Netherlands we use comma's in numbers where in other countries dots would be used. For example we use 39,99 and in other countries 39.99.
In a feed with prices we would have prices with such comma use, but I'm having trouble using those as numbers and rounding them by two digits behind the comma (or behind the dot really).
var num1 = "39,1234";
var num = parseInt(num1);
var n = num.toFixed(2);
console.log(n);
Here is such a number. I would like it to result in 39,12. They way I was thinking is then first use it as a string. Then turn that string into a number and use toFixed to round it of to two digets. But it results in 39,00 instead of 39,12.
Perhaps I'm thinking wrong and I should use some other way to make 39,1234 to be seen as 39.1234 so that it is rounded correctly as a number?
How can I used 39,1234 as a number 39,1234 instead of a string? So that I wouldn't have to go through a feed and replace commas by dots first in all my prices?
Edit: Regex version
Earlier I didn't realize that OP originally wanted it back to the format "xx,xx". This is a more elegant solution:
var num1 = "39,1234";
let n = num1.replace(/(?<=,\d{2})(\d*)$/,"");
console.log(n); //32,12
Regex explanation:
(?<=,\d){2} begins a lookbehind match for , followed by digits \d, 2 of them {2}. Lookbehind matches are not replaced.
(\d*)$ when we've found the lookbehind pattern, we match more digits \d, all * of them, till we reach end of string $. This is the match that will get replaced.
Original Solution
What you want is:
var num1 = "39,1234";
var n = parseFloat(num1.replace(",",".")).toFixed(2);
console.log(n); //39.12
// replaces it back to ",", but now it's a string!
n = n.replace(".",",")
console.log(n); //39,12
Explanation:
First replace "," with "." with replace()
Convert to float (not integer) with parseFloat()
Set to 2 decimal places with .toFixed(2)
Replace "." with ",". But now it's a string!
Note: this will not work if the currency value contains . as a thousandth separator. e.g. "40.200,1576". If that's the case, add another line num1 = num1.replace(".","") to strip out the separator before passing it to the parseFloat(...) line.
Try this
comdecimal= num1.replace(".","")
alert(comdecimal);
dotdecimal= comdecimal.replace(",",".")
alert(dotdecimal);
dotdecimal = Math.round(dotdecimal* 100) / 100;
alert(dotdecimal);
Since you're working with currency, I'd recommend using JS ES6 designated NumberFormat feature. Your code should look like this and be easily reused:
const formatter = new Intl.NumberFormat('nl-NL', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 2
});
console.log(formatter.format('145,53'.replace(',','.')));
//"€ 145,53"

Select 4 last digits in any string

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.

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.

I want regular expression to get only numbers

I want a regular expression to get only numbers from a string.I want to ignore the number preceding with a character.
Example : "(a/(b1/8))*100
Here I dont want to fetch b1.I want to get only the numbers like 8,100 etc
You can use a word boundary, though that would not match after underscores:
\b\d+
(?<![a-zA-Z])\d+ should work
You can use a regular expression to find both numbers with and without a leading character, and only keep the ones without:
var str = "(a/(b1/8))*100";
var nums = [], s;
var re = /([a-z]?)(\d+)/g;
while (s = re.exec(str)) {
if (!s[1].length) nums.push(s[2]);
}
alert(nums);
Output:
8, 100
Demo: http://jsfiddle.net/Guffa/23BnQ/
for only number
^(\d ? \d* : (\-?\d+))\d*(\.?\d+:\d*) $
this will accept any numeric value include -1.4 , 1.3 , 100 , -100
i checked it for my custom numeric validation attribute in asp net

Using JavaScript's parseInt at end of string

I know that
parseInt(myString, 10) // "Never forget the radix"
will return a number if the first characters in the string are numerical, but how can I do this in JavaScript if I have a string like "column5" and want to increment it to the next one ("column6")?
The number of digits at the end of the string is variable.
parseInt("column5".slice(-1), 10);
You can use -1 or -2 for one to two digit numbers, respectively.
If you want to specify any length, you can use the following to return the digits:
parseInt("column6445".match(/(\d+)$/)[0], 10);
The above will work for any length of numbers, as long as the string ends with one or more numbers
Split the number from the text, parse it, increment it, and then re-concatenate it. If the preceding string is well-known, e.g., "column", you can do something like this:
var precedingString = myString.substr(0, 6); // 6 is length of "column"
var numericString = myString.substr(7);
var number = parseInt(numericString);
number++;
return precedingString + number;
Try this:
var match = myString.match(/^([a-zA-Z]+)([0-9]+)$/);
if ( match ) {
return match[1] + (parseInt(match[2]) + 1, 10);
}
this will convert strings like text10 to text11, TxT1 to Txt2, etc. Works with long numbers at the end.
Added the radix to the parseInt call since the default parseInt value is too magic to be trusted.
See here for details:
http://www.w3schools.com/jsref/jsref_parseInt.asp
basically it will convert something like text010 to text9 which is not good ;).
var my_car="Ferrari";
var the_length=my_car.length;
var last_char=my_car.charAt(the_length-1);
alert('The last character is '+last_char+'.');
Credit to http://www.pageresource.com/jscript/jstring1.htm
Then just increment last_char
Split the word and number using RegEx.
using parseInt() increment the number.
Append to the word.
Just try to read string char by char, checking its ASCII code. If its from 48 to 57 you got your number. Try with charCodeAt function. Then just split string, increment the number and its done.

Categories