Page 1 of 1
Convert all string-integers into numbers
Posted: Sat Jan 07, 2017 11:22 am
by didakov88
Hi,
Here is a way to convert all integers from a string into numbers without using parseInt method.
Code: Select all
String.prototype.parseAllInt = function (){
//Array to hold the numbers
var numArray = [];
//Use replace to find all sequences of digits
this.replace( /\d+/g, function (a, b, c){
//When multiplying a coercion is made and the string is converted to number
//All numbers multiplied by 1 will return the same number
numArray.push ( a * 1 );
})
return numArray;
}
var myString = "125; 3; 49";
myString = myString.parseAllInt ();
alert ( typeof myString[0] );
Re: Convert all string-integers into numbers
Posted: Sat Jan 07, 2017 2:46 pm
by Kukurykus
Nice, but this way you are limited to only 3 numbers, or each time you will change length of function arguments in your protorype, so I changed it a little by adding few things, mainly a loop it let to use it with whatever amount of string numbers you want to convert it to sole numbers:
Code: Select all
Array.prototype.parseAllInt = function() {
for(arr = [], i = 0; i < this.split(';').length; i++) {
arr.push(eval(this[i].replace(/(\d+)/, '+$1')))
}
}
'125; 3; 49'.parseAllInt()
Just a note: there are now Array instead of String in prototype, and split method to change String to Array, I used also + characater in front of all strings what is equivalent to Number, and then for each iteration of loop I evaluated a result which got pushed to new array as a number.
Re: Convert all string-integers into numbers
Posted: Sat Jan 07, 2017 3:43 pm
by didakov88
Hi Kukurykus
It throws error "parseAllInt is not a function".
P.S. From what i know is good idea to avoid eval (don't remember the exact reason).
Re: Convert all string-integers into numbers
Posted: Sat Jan 07, 2017 4:35 pm
by Kukurykus
When you write html scripts I heard the same, but fortunately it's not HTML code. Anyway eval is about 30% of all my scripts, so far I didn't have problem with it.
I fixed that code, now it will be working, however I'll try later to make it simpler:
Code: Select all
Array.prototype.parseAllInt = function() {
for(arr = [], i = 0; i < this.length; i++) {
arr.push(eval(this[i].replace(/(\d+)/, '+$1')))
}
}
'125; 3; 49'.split(';').parseAllInt()
And here's final reconstructed version. Array is changed back to String, otherwise I had to keep .split method together with String Numbers. I had also made that variable I bound current this to:
Code: Select all
String.prototype.parseAllInt = function() {
for(arr = [], i = 0; i < (that = this.split(';')).length; i++) {
arr.push(eval(that[i].replace(/(\d+)/, '+$1')))
}
}
'125; 3; 49'.parseAllInt()