Format number using RegExp in javascript - javascript

I have a number like below
var number = '12345678904444'
and i want like this
(123) 456-7890x4444
Format is (###) ###-####x####.
How can i achieve this.

For what it's worth, this is what RegExp solution would look like ;-)
number.replace(/^(\d{3})(\d{3})(\d{4})(\d{4})$/, '($1) $2-$3x$4.');

You can use the javascript string split method :
var number = '12345678904444';
var numbers_array = numbers.split("");
Then you can use the array of the numbers to create a new string, following the format you want.
I'm sure you can do that !

If you want to format a number in Javascript, your best bet is to use String.slice() to extract the number parts you need, then contact them together using +.
DO NOT USE REGEX FOR THIS!! If your string in this has an error and can't be parsed properly, you run the risk of catastrophic backtracking, where your processing lasts really, really long.

I would prefer this:
var num = '1234567890x4444';
var first = num.substr(0,3), second = num.substr(3,3), last = num.substr(6);
var formatted = '('+first+') ' + second + '-'+ last;
Result:
console.log(formatted); // (123) 456-7890x4444

Related

JS Regex: how to remove first 2 zero's from "08/08/2017"

I'm new to regex, and have been researching all night how to remove the first 2 zeros from a string like "08/08/2017" (without removing 0 in "2017")
The 5+ regex tutorials I've reviewed do not seem to cover what I need here.
The date could be any sysdate returned from the system. So the regex also needs to work for "12/12/2017"
Here is the best I have come up with:
let sysdate = "08/08/2017"
let todayminuszero = str.replace("0","");
let today = todayminus0.replace("0","");
It works, but obviously it's unprofessional.
From the tutorials, I'm pretty sure I can do something along the lines of this:
str.replace(/\d{2}//g,""),);
This pattern would avoid getting the 3rd zero in str.
Replacement String would have to indicate 8/8/
Not sure how to write this though.
For date manipulation I would use other functions(best date related) but, this should do it, for the case that you stated. If you need other formats or so, I would suggest removing the zeros in an different way, but It all depends on you UseCase.
let sysdate = "08/08/2017";
let todayminuszero = sysdate.replace(/0(?=\d\/)/gi,"");
console.info(todayminuszero);
(?= ... ) is called Lookahead and with this you can see what is there, without replacing it
in this case we are checking for a number and a slash. (?=\d\/)
here some more information, if you want to read about lookahead and more http://www.regular-expressions.info/lookaround.html
A good place to test regex expressions is https://regex101.com/
I always use this for more advance expressions, since it displays all matching groups and so, with a great explaination. Great resource/help, if you are learning or creating difficult Expressions.
Info: as mentioned by Rajesh, the i flag is not needed for this Expression, I just use it out of personal preference. This flag just sets the expression-match to case insensitive.
-- Out of Scope, but may be interesting --
A longer solution without regex could look like this:
let sysdate = "08/08/2017";
let todayminuszero = sysdate.split("/").map(x => parseInt(x)).join("/");
console.info(todayminuszero);
Backside, this solution has many moving parts, the split function to make an array(´"08/08/2017"´ to ´["08", "08", "2017"]´), the map function, with a lambda function => and the parseInt function, to make out of each string item a nice integer (like: "08" to 8, ... ) and at last the join function that creates the final string out of the newly created integer array.
you should use this
let sysdate = "08/08/2017"
let todayminuszero = sysdate.replace(/(^|\/)0/g,"$1");
console.log(todayminuszero);
function stripLeadingZerosDate(dateStr){
return dateStr.split('/').reduce(function(date, datePart){
return date += parseInt(datePart) + '/'
}, '').slice(0, -1);
}
console.log(stripLeadingZerosDate('01/02/2016'));
console.log(stripLeadingZerosDate('2016/02/01'));
look at here
function stripLeadingZerosDate(dateStr){
return dateStr.split('/').reduce(function(date, datePart){
return date += parseInt(datePart) + '/'
}, '').slice(0, -1);
}
console.log(stripLeadingZerosDate('01/02/2016'));// 1/2/2016
console.log(stripLeadingZerosDate('2016/02/01'));// "2016/2/1"
By first 2 zeros, I understand you mean zero before 8 in month and in date.
You can try something like this:
Idea
Create a regex that captures group of number representing date, month and year.
Use this regex to replace values.
Use a function to return processed value.
var sysdate = "08/08/2017"
var numRegex = /(\d)+/g;
var result = sysdate.replace(numRegex, function(match){
return parseInt(match)
});
console.log(result)

Javascript timestamp formatting with regular expression?

how do i format a string of 2014-09-10 10:07:02 into something like this:
2014,09,10,10,07,02
Thanks!
Nice and simple.
var str = "2014-09-10 10:07:02";
var newstr = str.replace(/[ :-]/g, ',');
console.log(newstr);
Based on the assumption that you want to get rid of everything but the digits, an alternative is to inverse the regex to exclude everything but digits. This is, in effect, a white-listing approach as compared to the previously posted black-listing approach.
var dateTimeString = "2016-11-23 02:00:00";
var regex = /[^0-9]+/g; // Alternatively (credit zerkms): /\D+/g
var reformattedDateTimeString = dateTimeString.replace(regex, ',');
Note the + which has the effect of replacing groups of characters (e.g. two spaces would be replaced by only a single comma).
Also note that if you intend to use the strings as digits (e.g. via parseInt), numbers with a leading zero are interpreted within JavaScript as being base-8.

How can I use JavaScript's replace function to divide a matched number by 100?

I am trying to divide a regex-matched number in string format by 100 within JavaScript's replace function:
var number = "4354543";
var result = number.replace(/(\d+)/, '$1/100');
console.log(result); -> Printing 4354543/100
The answer should be 43545.43, but instead I'm getting "4354543/100".
Is it possible to achieve this?
You can use regular expressions for this, if that's what you're really after - for instance, lets say you want to divide numbers in a larger string by 100. To do this, you have to use the function callback, which lets you manipulate the captured groups in more complex ways:
var number = "abc 4354543 xyz";
var result = number.replace(/\d+/g, function(val) {
return +val/100;
});
console.log(result); //abc 43545.43 xyz
If you know that the input strings are at least 3 digits, a simple solution is to insert a decimal separator before the last 2 digits.
var number = "4354543";
var result = number.replace(/(\d+)(\d{2})/, '$1.$2');
console.log(result);
However, using a function as the second argument to .replace, as the answer by James Thorpe does, gives you more flexibility.
I think there is some confusion in your mind about what regex can do.
In your case you really don't need regex. Just do
var number = "4354543";
console.log(number/100);
You will see what you expect, js will change string to number(don't worry)
Regexp are not suitable for mathematic operations.
Use Number javascript class.
In your case
const number = '5485454845'; // Wathever
const result = Number(number) / 100;

Extracting numbers in a string in javascript

My app reads excel from a user. The app will receive "Quantity and Unit" of an item.
For Example,
5pcs.
12oz.
5lb.
I would like to get the number and store it in var qu[0].
I would like to get the string and store it in var qu[1].
How can i do it? I tried split. but only the number is taken.
You can get the number with an regular expression an the following pattern:
^(\d*)(.*)$
How to use regular expressions in Javascript
alert(Number("45a".match(/\d*/)) + 1)
https://jsfiddle.net/zep0tu0b/
Use parseInt or parseFloat to extract the number.
Then the remaining part should be the unit.
var num = parseFloat(str),
unit = str.substr(num.toString().length);
Consider checking if num is NaN, and then set unit to something else.

Help with a regular expression to capture numbers

I need to capture the price out of the following string:
Price: 30.
I need the 30 here, so I figured I'd use the following regex:
([0-9]+)$
This works in Rubular, but it returns null when I try it in my javascript.
console.log(values[1]);
// Price: 100
var price = values[1].match('/([0-9]+)$/g');
// null
Any ideas? Thanks in advance
Try this:
var price = values[1].match(/([0-9]+)$/g);
JavaScript supports RegExp literals, you don't need quotes and delimiters.
.match(/\d+$/) should behave the same, by the way.
See also: MDN - Creating a Regular Expression
Keep in mind there are simpler ways of getting this data. For example:
var tokens = values[1].split(': ');
var price = tokens[1];
You can also split by a single space, and probably want to add some validation.
Why don't you use this?
var matches = a.match(/\d+/);
then you can consume the first element (or last)
my suggestion is to avoid using $ in the end because there might be a space in the end.
This also works:
var price = values[1].match('([0-9]+)$');
It appears that you escaped the open-perens and therefore the regex is looking for "(90".
You don't need to put quotes around the regular expression in JavaScript.

Categories