print number with comma as hundred separator - javascript

I have a number like "7847258998" which I want to print with hundred comma separator in javascript.
The result should be:
7,84,72,58,998
i.e the first three digits from right should be grouped together. Remaining digits grouped in chunks of 2. I tried with following:
"7847258998".replace(/\B(?=(\d{3})+(\d{2})+(?!\d))/g, ",")
But it returns: 7,8,4,72,58998. What is the right expression?

Try this:
"7847258998".replace(/\B(?=(\d{2})*(\d{3})$)/g, ",");
I match the end of the string in the lookahead so that I'm always looking for something sane. Otherwise just about anything matches.
Tested on inputs length 1-10.. Enough to decide that it probably works. Pretty inefficient way to do it though, as for each character you have to parse the rest of the string.
But you did ask for a regular expression that does the job =)

function commafy(num)
{
num = num+"";
var re=/(-?\d+)(\d{3})/
while(re.test(num))
{
num=num.replace(re,"$1,$2")
}
return num;
}
function commafyback(num)
{
var x = num.split(',');
return parseFloat(x.join(""));
}
alert(commafy(7847258998))

You can convert the number to a locale string using the en-IN locale.
(7847258998).toLocaleString("en-IN")
If the value is a string, convert it to a number first:
const value = "7847258998"
Number(value).toLocaleString("en-IN")
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Related

How to parse number with points and commas

I recieve an string like;
1.234.567,89
I want 1234567.89
Comma is decimal delimiter.Point is thousands, and millions delimiter
I want to treat as a number.
I try replaces, but only works with first ".". And parseFloat.
Also I try some regex that found here,but doesn't work for me
I want this;
var numberAsString= '1.234.567,89';
//Step to clean string and conver to a number to compare (numberAsString => numberCleaned)
if (numberCleaned> 1000000) {alert("greater than 1 million");}
Any Idea?
(Sorry if its a newbie question, but I dont found any solution in hours...)
You can use replace with g
const val = '1.234.567,89'.replace(/\./gi, '').replace(/,/, '.');
console.log(val)
console.log(typeof parseFloat(val))
this should work for the current scenario.
1st remove the dots then replace the comma with dot.
let number = "1.234.567,89";
function parseNum(num){
return num.replace(/\./g, '').replace(",", ".")
}
console.log(parseNum(number));

check whether csv form or not [duplicate]

What is the regular expression to validate a comma delimited list like this one:
12365, 45236, 458, 1, 99996332, ......
I suggest you to do in the following way:
(\d+)(,\s*\d+)*
which would work for a list containing 1 or more elements.
This regex extracts an element from a comma separated list, regardless of contents:
(.+?)(?:,|$)
If you just replace the comma with something else, it should work for any delimiter.
It depends a bit on your exact requirements. I'm assuming: all numbers, any length, numbers cannot have leading zeros nor contain commas or decimal points. individual numbers always separated by a comma then a space, and the last number does NOT have a comma and space after it. Any of these being wrong would simplify the solution.
([1-9][0-9]*,[ ])*[1-9][0-9]*
Here's how I built that mentally:
[0-9] any digit.
[1-9][0-9]* leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ] as above, followed by a space
([1-9][0-9]*[ ])* as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]* as above, with a final number that doesn't have a comma.
Match duplicate comma-delimited items:
(?<=,|^)([^,]*)(,\1)+(?=,|$)
Reference.
This regex can be used to split the values of a comma delimitted list. List elements may be quoted, unquoted or empty. Commas inside a pair of quotation marks are not matched.
,(?!(?<=(?:^|,)\s*"(?:[^"]|""|\\")*,)(?:[^"]|""|\\")*"\s*(?:,|$))
Reference.
/^\d+(?:, ?\d+)*$/
i used this for a list of items that had to be alphanumeric without underscores at the front of each item.
^(([0-9a-zA-Z][0-9a-zA-Z_]*)([,][0-9a-zA-Z][0-9a-zA-Z_]*)*)$
You might want to specify language just to be safe, but
(\d+, ?)+(\d+)?
ought to work
I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:
"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"
I think this is an elegant solution, with a trick that avoids a lot of regex complexity:
if (string.IsNullOrEmpty(encodedValues))
{
return null;
}
else
{
var retVal = new Dictionary<int, string>();
var reFields = new Regex(#"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
foreach (Match match in reFields.Matches(encodedValues + ","))
{
var id = match.Groups[1].Value;
var value = match.Groups[2].Value;
retVal[int.Parse(id)] = value.Replace(",,", ",");
}
return retVal;
}
I think it can be adapted to the original question with an expression like #"([0-9]+),\s?" and parse on Groups[0].
I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!
In JavaScript, use split to help out, and catch any negative digits as well:
'-1,2,-3'.match(/(-?\d+)(,\s*-?\d+)*/)[0].split(',');
// ["-1", "2", "-3"]
// may need trimming if digits are space-separated
The following will match any comma delimited word/digit/space combination
(((.)*,)*)(.)*
Why don't you work with groups:
^(\d+(, )?)+$
If you had a more complicated regex, i.e: for valid urls rather than just numbers. You could do the following where you loop through each element and test each of them individually against your regex:
const validRelativeUrlRegex = /^(^$|(?!.*(\W\W))\/[a-zA-Z0-9\/-]+[^\W_]$)/;
const relativeUrls = "/url1,/url-2,url3";
const startsWithComma = relativeUrls.startsWith(",");
const endsWithComma = relativeUrls.endsWith(",");
const areAllURLsValid = relativeUrls
.split(",")
.every(url => validRelativeUrlRegex.test(url));
const isValid = areAllURLsValid && !endsWithComma && !startsWithComma

Determine if a string is only numbers or a comma

How can I determine if a string contains only numbers or a comma?
var x = '99,999,999';
var isMatch = x.match('/[\d|,]/');
The above always returns null.
To be a little more exact:
/^\d{1,3}(?:,\d{3})*$/
Only matches when the number is delimited by a comma after every 3rd digit from the right. (This doesn't account for decimals)
Try this: /^[\d,]+$/ Note that this will not tell you if the number is formatted correctly (i.e. ,99, will be accepted just as 99 or 9,999).
/^(?:\d{1,3}(?:,\d{3})*$|^\d+$)/ while more complex, this regex will test to see if the number is a properly formatted number (it won't accept ,,1,,,1,1111,,1,1,1 only 1,11,111,1,111,1111 etc.)

What are elegant ways to pair characters in a string?

For example, if the initial string s is "0123456789", desired output would be an array ["01", "23", "45", "67", "89"].
Looking for elegant solutions in JavaScript.
What I was thinking (very non-elegantly) is to iterate through the string by splitting on the empty string and using the Array.forEach method, and insert a delimeter after every two characters, then split by that delimeter. This is not a good solution, but it's my starting point.
Edit: A RegExp solution has been posted. I'd love to see if there are any other approaches.
How about:
var array = ("0123456789").match(/\w{1,2}/g);
Here we use .match() on your string to match any two or single ({1,2}) word characters (\w) and return an array of the results.
Regarding your edit for a non-regex solution; you could do a far less elegant function like this:
String.prototype.getPairs = function()
{
var pairs = [];
for(var i = 0; i < this.length; i += 2)
{
pairs[pairs.length] = this.substr(i, 2);
}
return pairs;
}
var array = ("01234567890").getPairs();
If you want to use split (and why not), you could do the following:
s.split(/([^][^])/).filter(function(x){return x})
Which splits using two consecutive characters as a delimiter (but because they're in a capture group, they're also part of split's result. Filtering that with the identity function serves to eliminate the empty strings (between the "delimiters"). Note that in the case of an odd number of characters, the last character will be output as a split, not a delimiter, but it doesn't matter since it will still test truthy.
([^] is how you spell . in javascript if you really want to match any character. I had to look that up.)

getting contents of string between digits

have a regex problem :(
what i would like to do is to find out the contents between two or more numbers.
var string = "90+*-+80-+/*70"
im trying to edit the symbols in between so it only shows up the last symbol and not the ones before it. so trying to get the above variable to be turned into 90+80*70. although this is just an example i have no idea how to do this. the length of the numbers, how many "sets" of numbers and the length of the symbols in between could be anything.
many thanks,
Steve,
The trick is in matching '90+-+' and '80-+/' seperately, and selecting only the number and the last constant.
The expression for finding the a number followed by 1 or more non-numbers would be
\d+[^\d]+
To select the number and the last non-number, add parens:
(\d+)[^\d]*([^\d])
Finally add a /g to repeat the procedure for each match, and replace it with the 2 matched groups for each match:
js> '90+*-+80-+/*70'.replace(/(\d+)[^\d]*([^\d])/g, '$1$2');
90+80*70
js>
Or you can use lookahead assertion and simply remove all non-numerical characters which are not last: "90+*-+80-+/*70".replace(/[^0-9]+(?=[^0-9])/g,'');
You can use a regular expression to match the non-digits and a callback function to process the match and decide what to replace:
var test = "90+*-+80-+/*70";
var out = test.replace(/[^\d]+/g, function(str) {
return(str.substr(-1));
})
alert(out);
See it work here: http://jsfiddle.net/jfriend00/Tncya/
This works by using a regular expression to match sequences of non-digits and then replacing that sequence of non-digits with the last character in the matched sequence.
i would use this tutorial, first, then review this for javascript-specific regex questions.
This should do it -
var string = "90+*-+80-+/*70"
var result = '';
var arr = string.split(/(\d+)/)
for (i = 0; i < arr.length; i++) {
if (!isNaN(arr[i])) result = result + arr[i];
else result = result + arr[i].slice(arr[i].length - 1, arr[i].length);
}
alert(result);
Working demo - http://jsfiddle.net/ipr101/SA2pR/
Similar to #Arnout Engelen
var string = "90+*-+80-+/*70";
string = string.replace(/(\d+)[^\d]*([^\d])(?=\d+)/g, '$1$2');
This was my first thinking of how the RegEx should perform, it also looks ahead to make sure the non-digit pattern is followed by another digit, which is what the question asked for (between two numbers)
Similar to #jfriend00
var string = "90+*-+80-+/*70";
string = string.replace( /(\d+?)([^\d]+?)(?=\d+)/g
, function(){
return arguments[1] + arguments[2].substr(-1);
});
Instead of only matching on non-digits, it matches on non-digits between two numbers, which is what the question asked
Why would this be any better?
If your equation was embedded in a paragraph or string of text. Like:
This is a test where I want to clean up something like 90+*-+80-+/*70 and don't want to scrap the whole paragraph.
Result (Expected) :
This is a test where I want to clean up something like 90+80*70 and don't want to scrap the whole paragraph.
Why would this not be any better?
There is more pattern matching, which makes it theoretically slower (negligible)
It would fail if your paragraph had embedded numbers. Like:
This is a paragraph where Sally bought 4 eggs from the supermarket, but only 3 of them made it back in one piece.
Result (Unexpected):
This is a paragraph where Sally bought 4 3 of them made it back in one piece.

Categories

Resources