regex replace value only keep numbers and limit decimal places to 2 - javascript

I have the following text "2345dsds34.000" and i want the following value '234534.00'. I plan to do this via regex replace but somehow it doesnt limit the decimal places to 2.
I am using this "2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '') but it keeps giving me 234534.000. How can i force it to limit it to 2 decimal points.
console.log("2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, ''))
Thanks

You can use toFixed JS Number function
Number( "2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '') ).toFixed(2)

You can simply slice the last digit off with .slice(0, -1):
console.log("2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '').slice(0, -1));

That regex is targetting the characters between some digits and some other digits having a decimal place.
Snapshot from https://regex101.com/
Then, the .replace() method is removing them. That all it does.
Since you don't know how many extra decimal you may have... I suggest you to use parseFloat() and .tofixed(2).
Please have a look at those two documentation links. ;)
var value = parseFloat("2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '')).toFixed(2);
console.log(value);

You can simply use
[^\d.]
let str = "2345dsds34.000"
let op = parseFloat(str.replace(/[^\d.]+/g, '')).toFixed(2)
console.log(op)

By using a Regex with capturing parentheses It will look like this
var regex = /(\d{4})[a-z]+(\d{2})\.(\d{2}).*/;
var input_chain = "2345dsds34.000";
var output = input_chain.replace(regex, "$1$2.$3");
console.log(output);
Each capturing parentheses can be references in the second part of the replace method by their position number prefixed with a $

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

Best way to remove thousand separators from string amount using a regex

I have variables that contain amounts and would like to remove the (US) thousand separators but also have to cover the scenario that there may be non-US formatted amounts where the comma is used for the decimals instead of for the thousands where I don't want to replace the comma.
Examples:
1,234,567.00 needs to become 1234567.00
1,234.00 needs to become 1234.00
but
1.234.567,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)
1.234,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)
I was thinking of using the following but wasn't sure about it as I am pretty new to Regex:
myVar.replace(/(\d+),(?=\d{3}(\D|$))/g, "$1");
What is best solution here? Note: I just need to cover normal amounts like the above examples, no special cases like letter / number combinations or things like 1,2,3 etc.
This one may suit your needs:
,(?=[\d,]*\.\d{2}\b)
Debuggex Demo
if (string.match(/\.\d{2}$/) {
string = string.replace(',', '');
}
or
string.replace(/,(?=.*\.\d+)/g, '');
Replace /,(?=\d*[\.,])/g with empty string?
http://regexr.com/39v2m
You can use replace() method to remove all the commas. They will be replaced with an empty string. I'm using reg exp with lookahead assertion to detect if a comma is followed by three digits, if so given comma will be removed.
string.replace(/,(?=\d{3})/g, '')
Examples:
'12,345,678.90'.replace(/,(?=\d{3})/g, '')
// '12345678.90'
'1,23,456.78'.replace(/,(?=\d{3})/g, '')
// '1,23456.78'
'$1,234.56'.replace(/,(?=\d{3})/g, '')
// '$1234.56'
This code is worked for me and you can use it in set amount val for remove separators
t.replace(/,(?=\d{3})/g, '')
myVar = myVar.replace(/([.,])(\d\d\d\D|\d\d\d$)/g,'$2');
Removes the period . or comma , when used as a thousand separator.

parseInt on (class=) "h310" renders NaN

I've an element like so
<span class='h310'>blah</span>
Now
console.log($(this).attr('class'));
renders
"h310"
but
console.log(parseInt($(this).attr('class')));
renders NaN instead of the very much needed 310.
What am I missing here and how to solve this?
UPDATE
The h is indeed static, I merely added it because "310" is not a valid class name according to the HTML spec while "h310" is.
The h is static
In that case you can simply replace the "h" and convert the string to a number using the unary plus:
+$(this).attr('class').replace('h', '');
> 310
JSFiddle demo.
You need to extract the number part of the string first. parseInt will only extract it automatically if there is no non-numeric character at the beginning of the string
var numberpart = $(this).attr('class').substring(1);
console.log(parseInt(numberpart, 10)); // make sure to provide the radix 10 for decimal numbers
parseInt method will not work here as the class contains the character "h".
Try this (with "h" is static)
<span id="sp1" class='h310'>blah</span>
$(document).ready(function(){
alert($('#sp1').attr('class'));
alert(parseInt($('#sp1').attr('class').replace('h', ''),10));
});
For a general solutions use regex.
console.log(parseInt($('#sp1').attr('class').match(/\d+/),10));
Live DEMO
Yes, obviously it returns NaN as parseInt method won't work for last number from string but if you have 310h then it could be parsed with parseInt:
So, use regular expression here:
console.log(parseInt($('span').attr('class').match(/\d+/),10));
working fiddle
As #James you can also use like this:
$(this).attr('class').replace(/[a-zA-Z ]/g, '');
Try this
var str= $('span').attr('class');
var thenum = str.replace( /^\D+/g, '');
console.log(thenum)
DEMO

Javascript regex match for string "game_1"

I just can't get this thing to work in javascript. So, I have a text "game_1" without the quotes and now i want to get that number out of it and I tried this:
var idText = "game_1";
re = /game_(.*?)/;
found = idText.match(re);
var ajdi = found[1];
alert( ajdi );
But it doesn't work - please point out where am I going wrong.
If you're only matching a number, you may want to try
/game_([0-9]+)/
as your regular expression. That will match at least one number, which seems to be what you need. You entered a regexp that allows for 0 characters (*) and let it select the shortest possible result (?), which may be a problem (and match you 0 characters), depending on the regex engine.
If this is the complete text, then there is no need for regular expressions:
var id = +str.split('_')[1];
or
var id = +str.replace('game_', '');
(unary + is to convert the string to a number)
If you insist on regular expression, you have to anchor the expression:
/^game_(.*?)$/
or make the * greedy by omitting the ?:
/game_(.*)/
Better is to make the expression more restrictive as #Naltharial suggested.
Simple string manipulation:
var idText = "game_1",
adji = parseInt(idText.substring(5), 10);
* means zero or more occurrences. It seems that combining it with a greediness controller ? results in zero match.
You could replace * with + (which means one or more occurrences), but as #Felix Kling notes, it would only match one digit.
Better to ditch the ? completely.
http://jsfiddle.net/G8Qt7/2/
Try "game_1".replace(/^(game_)/, '')
this will return the number
You can simply use this re /\d+/ to get any number inside your string

Using Regular Expressions with Javascript replace method

Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
strong text
Edit
strong text
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion!
Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
As an aside, all of this is much easier if you happen to be able to do lookbehind but almost every JS implementation doesn't.
Edit based on question update:
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
var y = x.replace(/(\d),(\d)/g, '$1$2');
I would use something like the following:
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
[0-9]{1,3}: 1 to 3 digits
(,[0-9]{3})*: [Optional] More digit triplets seperated by a comma
(\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards.
It seems to me you have three error conditions
",1000"
"1000,"
"1,,000"
If any one of these is true then you should reject the field, If they are all false then you can strip the commas in the normal way and move on. This can be a simple alternation:
^,|,,|,$
I would just remove anything except digits and the decimal separator ([^0-9.]) and send the output through parseFloat():
var y = parseFloat(x.replace(/[^0-9.]+/g, ""));
// invalid cases:
// - standalone comma at the beginning of the string
// - comma next to another comma
// - standalone comma at the end of the string
var i,
inputs = ['1,000.00', '1,000,00', ',000.00', '1,,000.00'],
invalid_cases = /(^,)|(,,)|(,$)/;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].match(invalid_cases) === null) {
// wipe out everything but decimal and dot
inputs[i] = inputs[i].replace(/[^\d.]+/g, '');
}
}
console.log(inputs); // ["1000.00", "100000", ",000.00", "1,,000.00"]

Categories

Resources