Change Letters into Numbers seperated by commas? - javascript

I am trying to create a button that displays the text from the "TextCollector" input as numbers seperated by commas and ignores any symbol that is not in the alphabet. Update: I also need it to ignore the fact that a letter is capitalized.
Example:
a = 1
b = 2
c = 3
and so on...
So if I typed in "cat's" in the input at the bottom would display "3,1,20,19".
Here's what I've tried so far:
<form action="">
<input type="text" id="TextCollector" name="TextCollector" placeholder="Type in something">
<br>
<input type="button" value="Submit" onclick="ShowMe()">
</form>
<h1 id="numbers"></h1>
<script>
function ShowMe() {
var text = document.getElementById("TextCollector").value;
var textnum = text.charCodeAt(0) - 97;
document.getElementById("numbers").innerHTML = textnum;
}
</script>
But the code I tried halfly works, it just displays the first letter as a number and ignores the rest. Also with my code "0" is "a", but I need "1" to be "a".
Can someone help me? I hope I made myself clear...

First .replace all non-alphabetical characters with the empty string, then you can turn the resulting string into an array, .map each character to its character code, and join it by commas:
function ShowMe() {
const replaced = document.getElementById("TextCollector").value.replace(/[^a-z]/gi, '').toLowerCase();
document.getElementById("numbers").textContent = [...replaced]
.map(char => char.charCodeAt(0) - 96)
.join(', ');
}
<form action="">
<input type="text" id="TextCollector" name="TextCollector" placeholder="Type in something">
<br>
<input type="button" value="Submit" onclick="ShowMe()">
</form>
<h1 id="numbers"></h1>

Allow me to introduce to you a few concepts which I highly recommend you learn instead of copy-pasting any code given to you. I'm not going to go into great detail because, honestly, all you have to know is how to ask the correct question on the google search bar to get your answer. I'll also talk about how you can develop a strategy to solving problems such as this one at the end of the post.
Loops
You use a loop in programming when you want to repeat a set of instructions multiple times. There are multiple ways to write a loop, the two most popular ways of writing a loop are: the for loop, and the while loop. Other less popular methods include do loop, recursion, etc.
Types
Javascript is weakly typed, which makes for a lot of weird and unexpected behavior i you try to add a bool value with an integer. Examples of primitive types are: Integer, Boolean, Char, String, etc. Numbers can be represented in multiple ways: integer, double, float. Don't worry too much about the differences between each of these, but if you need to use decimals and negative values, use floats. Boolean is either TRUE or FALSE. Char (short for Character) is a map between a number and a letter. (Read this document if you care to learn why your code outputs a "0" instead of a "1" when you run this line:
text.charCodeAt(0) - 97;
Operators
You should know what +, -, *, /, do grade school math class. You should also know > (greater than), < (less than), >= (greater than or equal), <= (less than or equal), == (equals), != (not equal), && (intersection, also known as AND), || (union, also known as OR). There are also some quality of life operators such as: ++ (increment value by 1), -- (decrement value by 1), += (increase target value by given amount), -= (decrease target value by given amount) etc etc....
THE ANSWER
Tie all this knowledge together, and we arrive at a solution.
string text = document.getElementById("TextCollector").value;
var i;
var textnum;
//create empty string variable to append char values to
var myString = '';
for (i = 0; i < text.length; i++)
{
//Convert char to number
textnum = text.charCodeAt(i) - 96;
//concatenate textnum to string, and add a comma at the end
myString = myString + textnum + ",";
}
//remove the last unwanted comma by applying "substr" method to the string
myString = myString.substr(0,myString.length - 1);
document.getElementById("numbers").innerHTML = textnum;
I encourage you to ask questions you do not understand from the solution above.
**Edit: The strategy to solving any problem is to break it down into sub-problems. Your goal is turn a bunch of characters from a string into numbers. Ask yourself these questions:
How can I turn characters into numbers?
Well, from the looks of your code it looks like you already knew how. Next question
How can I turn all characters into numbers, not just the starting character?
Ok, take a closer look to the method you applied to your "text" value
charCodeAt(0)
That zero represents the index of a string. A string is an array of char, and if you understand how arrays work, it should be no surprise why it only returns the first character.
Ok so, how can I apply this charCodeAt() method to ALL my characters?
This is a little tricky because if you don't know the concept of loops in programming (or recursion), you are not adequately equipped to solve these problems. There are many free online resources for learning basic programming concepts such as loops. I recommend this site here: https://www.w3schools.com/
Ok I can turn multiple characters to numbers. How do I glue them together into a single string?
This is something you can google. That's what I did. Hint: how to add chars to the end of a string
How do I get rid of the last comma in my string?
Google: How do I remove last char in a string?
Sources:
https://en.wikipedia.org/wiki/Control_flow#Loops
https://en.wikipedia.org/wiki/Primitive_data_type
https://www.w3schools.com/js/js_loop_for.asp
https://www.w3schools.com/js/js_string_methods.asp
https://codehandbook.org/remove-character-from-string/

Related

Applying currency format using replace and a regular expression

I am trying to understand some code where a number is converted to a currency format. Thus, if you have 16.9 it converts to $16.90. The problem with the code is if you have an amount over $1,000, it just returns $1, an amount over $2,000 returns $2, etc. Amounts in the hundreds show up fine.
Here is the function:
var _formatCurrency = function(amount) {
return "$" + parseFloat(amount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
};
(The reason the semicolon is after the bracket is because this function is in itself a statement in another function. That function is not relevant to this discussion.)
I found out that the person who originally put the code in there found it somewhere but didn't fully understand it and didn't test this particular scenario. I myself have not dealt much with regular expressions. I am not only trying to fix it, but to understand how it is working as it is now.
Here's what I've found out. The code between the backslash after the open parenthesis and the backslash before the g is the pattern. The g means global search. The \d means digit, and the (?=\d{3})+\. appears to mean find 3 digits plus a decimal point. I'm not sure I have that right, though, because if that was correct shouldn't it ignore numbers like 5.4? That works fine. Also, I'm not sure what the '$1,' is for. It looks to me like it is supposed to be placed where the digits are, but wouldn't that change all the numbers to $1? Also, why is there a comma after the 1?
Regarding your comment
I was hoping to just edit the regex so it would work properly.
The regex you are currently using is obviously not working for you so I think you should consider alternatives even if they are not too similar, and
Trying to keep the code change as small as possible
Understandable but sometimes it is better to use a code that is a little bit bigger and MORE READABLE than to go with compact and hieroglyphical.
Back to business:
I'm assuming you are getting a string as an argument and this string is composed only of digits and may or may not have a dot before the last 1 or 2 digts. Something like
//input //intended output
1 $1.00
20 $20.00
34.2 $34.20
23.1 $23.10
62516.16 $62,516.16
15.26 $15.26
4654656 $4,654,656.00
0.3 $0.30
I will let you do a pre-check of (assumed) non-valids like 1. | 2.2. | .6 | 4.8.1 | 4.856 | etc.
Proposed solution:
var _formatCurrency = function(amount) {
amount = "$" + amount.replace(/(\d)(?=(\d{3})+(\.(\d){0,2})*$)/g, '$1,');
if(amount.indexOf('.') === -1)
return amount + '.00';
var decimals = amount.split('.')[1];
return decimals.length < 2 ? amount + '0' : amount;
};
Regex break down:
(\d): Matches one digit. Parentheses group things for referencing when needed.
(?=(\d{3})+(\.(\d){0,2})*$). Now this guy. From end to beginning:
$: Matches the end of the string. This is what allows you to match from the end instead of the beginning which is very handy for adding the commas.
(\.(\d){0,2})*: This part processes the dot and decimals. The \. matches the dot. (\d){0,2} matches 0, 1 or 2 digits (the decimals). The * implies that this whole group can be empty.
?=(\d{3})+: \d{3} matches 3 digits exactly. + means at least one occurrence. Finally ?= matches a group after the main expression without including it in the result. In this case it takes three digits at a time (from the end remember?) and leaves them out of the result for when replacing.
g: Match and replace globally, the whole string.
Replacing with $1,: This is how captured groups are referenced for replacing, in this case the wanted group is number 1. Since the pattern will match every digit in the position 3n+1 (starting from the end or the dot) and catch it in the group number 1 ((\d)), then replacing that catch with $1, will effectively add a comma after each capture.
Try it and please feedback.
Also if you haven't already you should (and SO has not provided me with a format to stress this enough) really really look into this site as suggested by Taplar
The pattern is invalid, and your understanding of the function is incorrect. This function formats a number in a standard US currency, and here is how it works:
The parseFloat() function converts a string value to a decimal number.
The toFixed(2) function rounds the decimal number to 2 digits after the decimal point.
The replace() function is used here to add the thousands spearators (i.e. a comma after every 3 digits). The pattern is incorrect, so here is a suggested fix /(\d)(?=(\d{3})+\.)/g and this is how it works:
The (\d) captures a digit.
The (?=(\d{3})+\.) is called a look-ahead and it ensures that the captured digit above has one set of 3 digits (\d{3}) or more + followed by the decimal point \. after it followed by a decimal point.
The g flag/modifier is to apply the pattern globally, that is on the entire amount.
The replacement $1, replaces the pattern with the first captured group $1, which is in our case the digit (\d) (so technically replacing the digit with itself to make sure we don't lose the digit in the replacement) followed by a comma ,. So like I said, this is just to add the thousands separator.
Here are some tests with the suggested fix. Note that it works fine with numbers and strings:
var _formatCurrency = function(amount) {
return "$" + parseFloat(amount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
};
console.log(_formatCurrency('1'));
console.log(_formatCurrency('100'));
console.log(_formatCurrency('1000'));
console.log(_formatCurrency('1000000.559'));
console.log(_formatCurrency('10000000000.559'));
console.log(_formatCurrency(1));
console.log(_formatCurrency(100));
console.log(_formatCurrency(1000));
console.log(_formatCurrency(1000000.559));
console.log(_formatCurrency(10000000000.559));
Okay, I want to apologize to everyone who answered. I did some further tracing and found out the JSON call which was bringing in the amount did in fact have a comma in it, so it is just parsing that first digit. I was looking in the wrong place in the code when I thought there was no comma in there already. I do appreciate everyone's input and hope you won't think too bad of me for not catching that before this whole exercise. If nothing else, at least I now know how that regex operates so I can make use of it in the future. Now I just have to go about removing that comma.
Have a great day!
Assuming that you are working with USD only, then this should work for you as an alternative to Regular Expressions. I have also included a few tests to verify that it is working properly.
var test1 = '16.9';
var test2 = '2000.5';
var test3 = '300000.23';
var test4 = '3000000.23';
function stringToUSD(inputString) {
const splitValues = inputString.split('.');
const wholeNumber = splitValues[0].split('')
.map(val => parseInt(val))
.reverse()
.map((val, idx, arr) => idx !== 0 && (idx + 1) % 3 === 0 && arr[idx + 1] !== undefined ? `,${val}` : val)
.reverse()
.join('');
return parseFloat(`${wholeNumber}.${splitValues[1]}`).toFixed(2);
}
console.log(stringToUSD(test1));
console.log(stringToUSD(test2));
console.log(stringToUSD(test3));
console.log(stringToUSD(test4));

JavaScript: How to find and retrieve numbers from a string

I'm using RPG Maker MV which is a game creator that uses JavaScript to create plugins. I have a plugin in JavaScript already, however I'm trying to edit a part of the plugin so that it basically checks if a certain string exists in a character in the game and if it does, then sets specific variables to numbers within that string.
for (var i = 0; i < page.list.length; i++) {
if (page.list[i].code == 108 && page.list[i].parameters[0].contains("<post:" + (n) + "," + (n) + ">")) {
var post = page.list[i].parameters[0];
var array = post.split(',');
this._origMovement.x = Number(array[1]);
this._origMovement.y = Number(array[1]);
break;
};
};
So I know the first 2 lines work and contains works when I only put a specific string. However I can't figure out how to check for 2 numbers that are separated by a comma and wrapped in '<>' tags, without knowing what the numbers would be.
Then it needs to extract those numbers and assign one to this._origMovement.x and the other to this._origMovement.y.
Any help would be greatly appreciated.
This is one of those rare cases where I'd use a regular expression. If you haven't come across regular expressions before I suggest reading an introduction to them, such as this one: https://regexone.com/
In your case, you probable want something like this:
var myRegex = /<post:(\d+),(\d+)>/;
var matches = myParameter.match(myRegex);
this._origMovement.x = matches[1]; //the first number
this._origMovement.y = matches[2]; //the second number
The myRegex variable is a regular expression that looks for the pattern you describe, and has 2 capture groups which look for a string of one or more digits (\d+ means "one or more digits"). The result of the .match() call gives you an array containing the entire match and the results of the capture groups.
If you want to allow for decimal numbers, you'll need to use a different capture group that allows for a decimal point, such as ([\d\.]+), which means "a sequence of one or more digits and decimal points", or more sophisticated, (\d+\.?\d*), which is "a sequence of one or more digits, following by an optional decimal point, followed by zero or more digits).
There are lots of good tutorials around to help you write good regular expressions, and sites that will help you live-test your expressions to make sure they work correctly. They're a powerful tool, but be careful not to over-use them!
Got it to work. For anyone who may ever be interested, the code is below.
for (var i = 0; i < page.list.length; i++) {
if (page.list[i].code == 108 && page.list[i].parameters[0].contains("<post:")) {
var myRegex = /<post:(\d+),(\d+)>/;
var matches = page.list[i].parameters[0].match(myRegex);
this._origMovement.x = matches[1]; //the first number
this._origMovement.y = matches[2]; //the second number
break;
}
};

Stuck on finding a largest/greatest number in an array

I have been trying to get a whole array to populate the greatest number within it and I am stumbling.
In my HTML code, I have a number input box where a user can enter it and an alert populate once a user clicks on the "button":
<label for="numbers">Enter numbers seperated by a space.</label><input type="text" size="20" id="numbers">
<div id="greatestbutton" class="button">Click here to get the Greatest Number!</div>
<div>The greatest number is in the alert box.<span id="numbers"></span></div>
In my JS Code, I can get it to recognize the parseFloat, only if the non digit is the first character in the input box, for example "i782" will populate NaN in the alert box, but "7i82", will only populate a 7 in the alert box.
Furthermore, I am unable to get it to go past the first space " ". I am thoroughly stumped and I am also confused that if I put the alert to the var (greatest), it just comes back as 0, yet when I put in alert(array) I at least get something that I hve entered. I know I am missing a step somewhere, but I totally lost.
Any help would be greatly appreciated!!! Thanks!!.
var button = document.getElementById("greatestbutton");
button.onclick = function greaterNumber() {
var array = parseFloat(document.getElementById('numbers').value);
var greatest = 0;
for (i = 0; i < array.length; i++){
if (array[i] > greatest){
var greatest = Math.max(array[i])};
}
alert(array);
}
There's a couple things going wrong here.
For starters, what you want to do is find each valid textual representation of a number in the input box. This is a bit trickier than it sounds - do you want to support negative numbers? Decimal places?
Enter the Regular Expression, one of the most useful inventions in the history of programming. Using a regular expression one can, without too much difficulty, extract all the valid numeric sequences from strings like abc-.02dflaxoe042xne+3.14-5 ( -0.2, 042, +3.14, and -5, that is - all of which can be parsed by parseFloat individually.
This regex does the trick:
/[-+]?(\d+(\.\d+)?|\.\d+)/g
It matches an optional leading - or + ( [-+]? ), followed by either
\d+(\.\d+)?: one or more decimal number 0-9 ( \d ) followed optionally by a decimal point ( \. )and one or more decimal numbers
or
a decimal point \. followed by one or more decimal numbers
The first case matches +3.2, -31, -0.0001, 51, or 42 - the second matches .2, -.1, or +.31. That second case is a bit unusual (no decimal numbers before the decimal point ) but since parseFloat could read them I added them in.
Some might argue that there's a simpler way to write this - I do wish I could combine the either/or, but I couldn't figure out a better regex that made sure that at least one numeric character was supplied. Edits welcome.
The parsing trick, trick, as you were approaching, is to parse out all the numeric substrings first, then parse each into a floating point number and compare. You had some of the right ideas, but there were still some things missing.
Math.max() takes one or more numeric arguments, but can't take an array, unfortunately. It would make a lot of sense if it could, but it can't. I didn't try to find a way around this, though there might be one, because I had to parse each of the numeric strings anyway, I just took max() out completely and used the > operator instead.
A general programming point now: when you're looking for the greatest, don't make assumptions like starting the search at 0. In your example, if no numbers are supplied, or all negative numbers, then the greatest number is your starting point of 0 - which the user may not even have inputted. I initialized my greatest to undefined and then handled that case below.
A bit of further help:
var button = document.getElementById("greatestbutton");
button.onclick = function greaterNumber() {
is a long way of using a variable to say
document.getElementById("greatestbutton").onclick = function greaterNumber() {
You'll notice that you have both the output <span> and the <input> field ( which should end with />, by the way) with an id of numbers - you can't refer to two elements with the same ID of course.
Finally, a semantic point ( :-) ): As a believer in the semantic principles of markup, I'll ask you to avoid all-too-common anti-patterns such as <div id="greatestbutton" class="button">. There is already a <button> tag, and users will be told it's a button even if they're on a braille terminal or other such devices - a <div class='button'> loses this semantic meaning regardless of how pretty you make it with CSS. For the same reason, I replaced your <span> with a <kbd> tag ( for "typed input").
Here's what I came up with:
<script type='text/javascript'>
greaterNumber = function () {
var array = document.getElementById('numbers').value.match(/[-+]?(\d+(\.\d+)?|\.\d+)/g)
alert(array)
if (!array || array.length <= 0) return; // no numbers at all!
var greatest = undefined
if (array.type == 'number') // only one number
array = [array] // convert to array for simplicity
for (var i in array) {
array[i] = parseFloat(array[i])
if (greatest == undefined || array[i] > greatest) greatest = array[i]
}
document.getElementById('greatest').innerHTML = greatest;
}
</script>
</head>
<body>
<p>
<label for="numbers">Enter numbers seperated by a space:</label>
<input type="text" size="20" id="numbers" />
</p>
<p>
<button id="greatestbutton" onclick="greaterNumber()">Click here to get the Greatest Number!</button>
</p>
<div>The greatest number is in the alert box: <kbd id="greatest">?</kbd>
</div>
</html>
See a working example here: http://jsfiddle.net/7JN74/10/

How to check if a string contains a number in JavaScript?

I don't get how hard it is to discern a string containing a number from other strings in JavaScript.
Number('') evaluates to 0, while '' is definitely not a number for humans.
parseFloat enforces numbers, but allow them to be tailed by abitrary text.
isNaN evaluates to false for whitespace strings.
So what is the programatically function for checking if a string is a number according to a simple and sane definition what a number is?
By using below function we can test whether a javascript string contains a number or not. In above function inplace of t, we need to pass our javascript string as a parameter, then the function will return either true or false
function hasNumbers(t)
{
var regex = /\d/g;
return regex.test(t);
}
If you want something a little more complex regarding format, you could use regex, something like this:
var pattern = /^(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
Demo
I created this regex while answering a different question awhile back (see here). This will check that it is a number with atleast one character, cannot start with 0 unless it is 0 (or 0.[othernumbers]). Cannot have decimal unless there are digits after the decimal, may or may not have commas.. but if it does it makes sure they are 3 digits apart, etc. Could also add a -? at the beginning if you want to allow negative numbers... something like:
/^(-)?(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
There's this simple solution :
var ok = parseFloat(s)==s;
If you need to consider "2 " as not a number, then you might use this one :
var ok = !!(+s==s && s.length && s.trim()==s);
You can always do:
function isNumber(n)
{
if (n.trim().length === 0)
return false;
return !isNaN(n);
}
Let's try
""+(+n)===n
which enforces a very rigid canonical way of the number.
However, such number strings can be created by var n=''+some_number by JS reliable.
So this solution would reject '.01', and reject all simple numbers that JS would stringify with exponent, also reject all exponential representations that JS would display with mantissa only. But as long we stay in integer and low float number ranges, it should work with otherwise supplied numbers to.
No need to panic just use this snippet if name String Contains only numbers or text.
try below.
var pattern = /^([^0-9]*)$/;
if(!YourNiceVariable.value.match(pattern)) {//it happen while Name Contains only Charectors.}
if(YourNiceVariable.value.match(pattern)) {//it happen while Name Contains only Numbers.}
This might be insane depending on the length of your string, but you could split it into an array of individual characters and then test each character with isNaN to determine if it's a number or not.
A very short, wrong but correctable answer was just deleted. I just could comment it, besides it was very cool! So here the corrected term again:
n!=='' && +n==n'
seems good. The first term eliminates the empty string case, the second one enforces the string interpretataion of a number created by numeric interpretation of the string to match the string. As the string is not empty, any tolerated character like whitespaces are removed, so we check if they were present.

Regular expression to strip thousand separator from numeral string?

I have strings which contains thousand separators, however no string-to-number function wants to consume it correctly (using JavaScript). I'm thinking about "preparing" the string by stripping all thousand separators, leaving anything else untoched and letting Number/parseInt/parseFloat functions (I'm satisfied with their behavious otherwise) to decide the rest. But it seems what i have no idea which RegExp can do that!
Better ideas are welcome too!
UPDATE:
Sorry, answers enlightened me how badly formulated question it is. What i'm triyng to achieve is: 1) to strip thousand separators only if any, but 2) to not disturb original string much so i will get NaNs in the cases of invalid numerals.
MORE UPDATE:
JavaScript is limited to English locale for parsing, so lets assume thousand separator is ',' for simplicity (naturally, it never matches decimal separator in any locale, so changing to any other locale should not pose a problem)
Now, on parsing functions:
parseFloat('1023.95BARGAIN BYTES!') // parseXXX functions just "gives up" on invalid chars and returns 1023.95
Number('1023.95BARGAIN BYTES!') // while Number constructor behaves "strictly" and will return NaN
Sometimes I use rhw loose one, sometimes strict. I want to figure out the best approach for preparing string for both functions.
On validity of numerals:
'1,023.99' is perfectly well-formed English number, and stripping all commas will lead to correct result.
'1,0,2,3.99' is broken, however generic comma stripping will give '1023.99' which is unlikely to be a correct result.
welp, I'll venture to throw my suggestion into the pot:
Note: Revised
stringWithNumbers = stringwithNumbers.replace(/(\d+),(?=\d{3}(\D|$))/g, "$1");
should turn
1,234,567.12
1,023.99
1,0,2,3.99
the dang thing costs $1,205!!
95,5,0,432
12345,0000
1,2345
into:
1234567.12
1023.99
1,0,2,3.99
the dang thing costs $1205!!
95,5,0432
12345,0000
1,2345
I hope that's useful!
EDIT:
There is an additional alteration that may be necessary, but is not without side effects:
(\b\d{1,3}),(?=\d{3}(\D|$))
This changes the "one or more" quantifier (+) for the first set of digits into a "one to three" quantifier ({1,3}) and adds a "word-boundary" assertion before it. It will prevent replacements like 1234,123 ==> 1234123. However, it will also prevent a replacement that might be desired (if it is preceded by a letter or underscore), such as A123,789 or _1,555 (which will remain unchanged).
A simple num.replace(/,/g, '') should be sufficient I think.
Depends on what your thousand separator is
myString = myString.replace(/[ ,]/g, "");
would remove spaces and commas.
This should work for you
var decimalCharacter = ".",
regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
num = "10,0000,000,000.999";
+num.match(regex).join("");
To confirm that a numeral-string is well-formed, use:
/^(\d*|\d{1,3}(,\d{3})+)($|[^\d])/.test(numeral_string)
which will return true if the numeral-string is either (1) just a sequence of zero or more digits, or (2) a sequence of digits with a comma before each set of three digits, or (3) either of the above followed by a non-digit character and who knows what else. (Case #3 is for floats, as well as your "BARGAIN BYTES!" examples.)
Once you've confirmed that, use:
numeral_string.replace(/,/g, '')
which will return a copy of the numeral-string with all commas excised.
You can use s.replaceAll("(\\W)(?=\\d{3})","");
This regex gets all alpha-numeric character with 3 characters after it.
Strings like 4.444.444.444,00 € will be 4444444444,00 €
I have used the following in a commercial setting, and it has worked often:
numberStr = numberStr.replace(/[. ,](\d\d\d\D|\d\d\d$)/g,'$1');
In the above example, thousands can be marked with a decimal, a comma, or a space.
In some cases ( like a price of 1000,5 Euros) the above doesn't work. If you need something more robust, this should work 100% of the time:
//convert a comma or space used as the cent placeholder to a decimal
$priceStr = $priceStr.replace(/[, ](\d\d$)/,'.$1');
$priceStr = $priceStr.replace(/[, ](\d$)/,'.$1');
//capture cents
var $hasCentsRegex = /[.]\d\d?$/;
if($hasCentsRegex.test($priceStr)) {
var $matchArray = $priceStr.match(/(.*)([.]\d\d?$)/);
var $priceBeforeCents = $matchArray[1];
var $cents = $matchArray[2];
} else{
var $priceBeforeCents = $priceStr;
var $cents = "";
}
//remove decimals, commas and whitespace from the pre-cent portion
$priceBeforeCents = $priceBeforeCents.replace(/[.\s,]/g,'');
//re-create the price by adding back the cents
$priceStr = $priceBeforeCents + $cents;

Categories