JavaScript separate currency into number value and currency symbol/name - javascript

I am getting a currency value from a web service, that I would like to display in a number input (the float part) and it's currency symbol/name on a simple label that's next to the input.
Example of data that I get from the web service:
$ 1.200,05
R$ 1200.05
kr. 1,200.05
37,200.05 kr.
$300
500.0 €
You can see that the data is very mixed.
The symbol/currency name can be before or after the number value, it can have a space between the symbol and the number, or no space at all. It can also have a dot inside the currency name, that I would still like to keep (like with the danish krone: kr.)
The decimal mark can either be a '.' or a ',' and it can be followed by any number of decimals.
Same with the thousand separator: it can be either a '.' or a ','
I have the following snippet to get the number value, but i'm having trouble getting the currency string part:
if (!isNaN(cost.charAt(0))) { //check whether it starts with number or string, to adjust the regex
var regex = /([+-]?[0-9|^.|^,]+)[\.|,]([0-9])/
var result = regex.exec(cost);
var floatResult = result? result[1].replace(/[.,]/g, "")+ "." + result[2] : cost.replace(/[^0-9-+]/g, "");
return floatResult;
}
else {
var regex = /([+-]?[0-9|^.|^,]+)[\.|,]([0-9]+)$/igm
var result = regex.exec(cost);
var floatResult = result? result[1].replace(/[.,]/g, "")+ "." + result[2] : cost.replace(/[^0-9-+]/g, "");
return floatResult;
}
I am using jQuery and AngularJS in my webapp, so if there's an easier method with the help of one of those, it would be nice.

I'm not sure how to use regex to do this, but what I might do without regex is:
a) record the index of the first numeric character
b) record the index of the last numeric character
c) take the substring from the first to last numeric characters and convert that to a Number, Number(numerics) (you will have to remove commas between numbers for this step)
d) if the first numeric character index is 0, the currency symbol/name will be at the end of the string, after the last numeric character
e) otherwise it will be at the front of the string, before the first numeric character.
edit
you may be able to simplify the whole thing if you can be certain that what you get back as a response always contains one space that seperates the value and the currency symbol. If that were true (as it is in your examples), you could just use string.split(' ') to get an array of the two strings, and check which one is the number.

Related

how to substring in javascript but excluding symbols

I need to use (substring method) in my javascript web network project, but excluding : colon symbol, because it is hexadecimal ip address, and I don't want to accept : colons as a string or lets say number in the substring, I want to ignore it. How to do that?
This is the example IPV6 in the input field:
2001:2eb8:0dc1:54ed:0000:0000:0000:0f31
after substring from 1 to 12:
001:2eb8:0d
as you can see it accepted colons also, but in fact, I need this result:
2001:2eb8:0dc1
so by excluding these two symbols, it would have gave me that result above, but I don't know how.
and here is the code, IpAddressInput, is only a normal input field which I write the ip address in it.
Here is the code:
var IpValue = $('#IpAddressInput').val();
alert(IpValue.substr(1, (12) -1));
Answer 1: I think there is no direct function to results like you want but this answer will help you. I counted the number of colons from index 0 to 12 and then slice the source string from 0 to 12 plus the number. Here is the code:
let val = "2001:2eb8:0dc1:54ed:0000:0000:0000:0f31";
let numOfColons = val.slice(0, 12).match(/:/g).length;
let result = val.slice(0, 12 + numOfColons);
console.log(result)
Answer 2: If you are sure that there is a colon after exactly every 4 characters, a better solution will be this. The idea is to remove all colons from the string, slice from index 0 to 12, and add a colon after every 4 characters. Finally, it removes the last colon. Here is the code:
let value = "2001:2eb8:0dc1:54ed:0000:0000:0000:0f31";
let valueExcludeColon = value.replace(/:/g, ''); // '20012eb80dc154ed0000000000000f31'
let result = valueExcludeColon.slice(0,12).replace(/(.{4})/g, "$1:"); // '2001:2eb8:0dc1:'
let finalResult = result.slice(0, -1); // 2001:2eb8:0dc1
console.log(finalResult)

Remove certain re-occurring characters from a string

I am quite new to JS and i have a problem:
I am trying to compare a string (as integer) with an input (as integer). The problem occurs because, the string is written as 10'000'000 for e.g. and the integer as 10000000, with 4 possible scenarios:
- 1'000'000
- 10'000'000
- 100'000'000
- 1'000'000'000
That is, the number (as string) can be from 1 million to 1 billion.
I want to erase (or replace with "") all of my " ' " characters so that the format which i will get for the string will be the same as the one of the integer
E.g. Integer: 95500000 String: 95'500'000 ---> need it to be 95500000
A similar solution but not quite the same is provided here:
Regex remove repeated characters from a string by javascript
String: 95'500'000 ---> need it to be 95500000
That’s as simple as "95'500'000".replace(/'/g, '')
g modifier makes it replace all occurrences, and not just the first one.
const str = "9'0'0000"
const removedSlashStr = str.split('').reduce((removedSlash, char) => {
if(char !== "'") removedSlash+=char
return removedSlash
}, '')
console.log(removedSlashStr) // "900000"

How to remove the first character from a string if it's a non-number in JavaScript?

I have a text field on a form that allows individuals to enter a price. I'm trying to allow other currency symbols to be entered into this field but my logic behind the scenes needs to strip out any currency symbols.
To make it easier, I really only care about the first character and only if it's a non number.
Otherwise, I can't use a solution that would remove any decimal points or commas in my price field or my calculations won't work.
Update: I'm currently using
itemCost = itemCost.replace(/\$/, '');
But now I'm trying to open it up to any currency sign.
You can access a string in the same way as you would an array. Take a look at the character at position zero of the string -
var inputString = '...' // whatever the user entered
var firstChar = inputString[0];
if (!Number.isInteger(firstChar)) {
inputString = inputString.substr(1)
}
I'm using the String.subStr function here to create a copy of the string starting from the 1st index.
Please take into consideration though that solution assumes that the provided string will only ever have one currency symbol. Inputs such as "USD $1.00" or even " $1.00" will not work with this solution.
An alternative would be to remove any character that is non numeric (excluding decimal points and commas) from the entire input string.
var inputString = '...' // whatever the user entered
var priceString = inputString.replace(/[^0-9\.,]/, '')
// $1.00 -> 1.00
// USD #$1,000.00 -> 1,000.00
Why don't you whitelist characters instead?
'$99,99'.match(/[0-9]+[,.]{0,1}[0-9]*/)
You'll certainly want to perfect it, I wrote it fast...
What the suggested regex does is make sure we have one or more digits, then maybe either a , or a . and 0 or more digits.
What I mostly want to point out with this answer is, while keeping just numeric characters is easy, it will by no mean make certain that the user entered a correct currency. The is also no way to know if the user entering 1,337 meant 1,337.00 or 1.337
There's a few ways you can do this... One way is to make the input into an array, check isNaN on the first element, and strip it if it's not a number.
const input = '$123.45';
const otherInput = '23.34';
function splitCheck(someInput) {
let arrayInput = someInput.split('');
if (isNaN(arrayInput[0])) {
arrayInput.shift();
return arrayInput.join('');
} else {
return someInput;
}
}
splitCheck(input); // returns 123.45
splitCheck(otherInput); // returns 23.34
Note you can also use a regexp, or you can also check for ASCII character values across an array, but this is just the first that came to mind.
A Javscript function could be
// Function to check first letter as numbers
function chkNumeric(inputtxt)
{
var letterNumber = '^[0-9]{1,}[ a-zA-Z0-9]*$';
if((inputtxt.value.match(letterNumber))
{
return true;
}
else
{
return false;
}
}
You may use parseInt()
parseInt() parses a string and returns an integer.
If the first character cannot be converted to a number, parseInt() returns NaN.
parseInt('Hello') // returns NaN
Also it's a good idea to trim() the string before using parseInt()
var money = '$123.45';
if( money ) { // check if variable is not null
money = money.trim();
}
console.log(parseInt(money));
// check NaN using isNaN function
if(isNaN(parseInt(money))) {
console.log('first charatcer is not a number')
money = money.substr(1);
console.log(money);
}
else {
console.log('first charatcer is a number')
}

Split a string based on a condition

I would like to split a spreadsheet cell reference (eg, A10, AB100, ABC5) to two string parts: column reference and row reference.
A10 => A and 10
AB100 => AB and 100 ...
Does anyone know how to do this by string functions?
var res = "AA123";
//Method 1
var arr = res.match(/[a-z]+|[^a-z]+/gi);
document.write(arr[0] + "<br>" + arr[1]);
//Method 2 (as deceze suggested)
var arr = res.match(/([^\d]+)(\d+)/);
document.write("<br>" + arr[1] + "<br>" + arr[2]);
//Note here [^\d] is the same as \D
This is easiest to do with a regular expression (regex). For example:
var ref = "AA100";
var matches = ref.match(/^([a-zA-Z]+)([1-9][0-9]*)$/);
if (matches) {
var column = matches[1];
var row = Number(matches[2]);
console.log(column); // "AA"
console.log(row); // 100
} else {
throw new Error('invalid ref "' + ref + '"');
}
The important part here is the regex literal, /^([a-zA-Z]+)([1-9][0-9]*)$/. I'll walk you through it.
^ anchors the regex to the start of the string. Otherwise you might match something like "123ABC456".
[a-zA-Z]+ matches one or more character from a-z or A-Z.
[1-9][0-9]* matches exactly one character from 1-9, and then zero or more characters from 0-9. This makes sure that the number you are matching never starts with zero (i.e. "A001" is not allowed).
$ anchors the regex to the end of the string, so that you don't match something like "ABC123DEF".
The parentheses around ([a-zA-Z]+) and ([1-9][0-9]*) "capture" the strings inside them, so that we can later find them using matches[1] and matches[2].
This example is strict about only matching valid cell references. If you trust the data you receive to always be valid then you can get away with a less strict regex, but it is good practice to always validate your data anyway in case your data source changes or you use the code somewhere else.
It is also up to you to decide what you want to do if you receive invalid data. In this example I make the script throw an error, but there might be better choices in your situation (e.g. prompt the user to enter another value).

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

Categories

Resources