how to get numeric value from string? - javascript

This will alert 23.
alert(parseInt('23 asdf'));
But this will not alert 23 but alerts NaN
alert(parseInt('asdf 23'));
How can I get number from like 'asd98'?

You can use a regex to get the first integer :
var num = parseInt(str.match(/\d+/),10)
If you want to parse any number (not just a positive integer, for example "asd -98.43") use
var num = str.match(/-?\d+\.?\d*/)
Now suppose you have more than one integer in your string :
var str = "a24b30c90";
Then you can get an array with
var numbers = str.match(/\d+/g).map(Number);
Result : [24, 30, 90]
For the fun and for Shadow Wizard, here's a solution without regular expression for strings containing only one integer (it could be extended for multiple integers) :
var num = [].reduce.call(str,function(r,v){ return v==+v?+v+r*10:r },0);

parseInt('asd98'.match(/\d+/))

function toNumeric(string) {
return parseInt(string.replace(/\D/g, ""), 10);
}

You have to use regular expression to extract the number.
var mixedTextAndNumber= 'some56number';
var justTheNumber = parseInt(mixedTextAndNumber.match(/\d+/g));

var num = +('asd98'.replace(/[a-zA-Z ]/g, ""));

Related

Javascript getting number from string

I have a string:
var example = 'sorted-by-' + number;
Where number variable can be any positive integer. I don't know how to reverse this process, not knowing how many digits this number has. I want to get from example string a number at the end.
var outputNumber = example.substring(10);
This is the simple solution because example string always start with 'sorted-by-'.
let num = + string.substr(10);
You can use String#replace function to replace sorted-by- to empty string and after that convert left part to a number:
var example = 'sorted-by-' + 125;
var num = +example.replace('sorted-by-', '');
console.log(num);
You can split string at - and get last element using pop().
var example = 'sorted-by-' + 100.99
var n = +(example.split('-').pop())
console.log(n)
You can also use regex for this.
var number = 245246245;
var example = 'sorted-by-' + number;
var res = example.match(/^sorted-by-(\d+)/);
console.log(+res[1]);

how to replace a string which is not integer using regex in javascript

i have use this regex try to replace a string which is not a integer ,however it replace when it is a integer.
this.v=function(){this.value=this.value.replace(/^(-?[1-9]\d*|0)$/,'');}
what is the opposite regex? :what is the regex for replace a string which is not a integer with "".
eg:if user entered string is not -2,0,1,123 such like that i want clear the input.if string like 2e3r,2.5,-1.3 the input will be clear
value
If you must use regex then the following should work. Not tested for efficiency, just thrown together.
var numbersOnly = function(number_string) {
var re = /(\+?|\-?)([0-9]+)(\.[0-9]+)*/g;
return number_string.match(re);
}
numbersOnly('pears1.3apples3.2chinesefood-7.8');
// [ '1.3', '3.2', '-7.8' ]
i have solved this one by changing the function logic:
onblur="(this.v=function(){var re=/^(-?[1-9]\d*|0)$/;if(!re.test(this.value)){this.value=''}}).call(this)
You could sanitize user input using parseInt or Number methods. For example:
var normalInput = "1";
normalInput = parseInt(normalInput, 10);
console.log(normalInput); // prints 1
var wrongInput = "12a23-24";
wrongInput = parseInt(wrongInput, 10);
console.log(wrongInput); // prints 12 (stops after first not valid number)
Or something like that:
var myInput = "21312312321",
processedInput = Number(myInput);
if(processedInput !== NaN){ // if number given is a valid number return it (also works for float input)
console.log(processedInput);
return processedInput;
}
else{ // otherwise return an empty string
return "";
}
Jsfiddle example1 example2.
To remove all non-digit characters in the string:
this.v=function(){this.value=this.value.replace(/\D+/g,'');}

How to get ASCII of number in JavaScript?

I am aware of name.charCodeAt(0). I am having issued with the following code, so I want a solution for below.
var number= 2;
var t = number.charCodeAt(0);
console.log(t);
The answer needs to be in ASCII. I am getting the log as 2 and not as ASCII value 50. What can be the issue?
ASCII is a way of representing String data. You need to first convert your Number to String;
Remember also that String can have arbitrary length so you'll need to iterate over every character.
var x = 2,
str_x = '' + x,
chrs = Array.prototype.map.call(str_x, function (e) {return e.charCodeAt(0);});
chrs; // [50]
Finally, JavaScript works with UTF-16/UCS-2 and not plain ASCII. Luckily the values for digits are the same in both so you don't have to do any further transformation here.
You have to cast a number to a string first to use .charCodeAt to get the numerical character code.
var number = 2;
var t = String( number ).charCodeAt( 0 );
console.log( t ); // 50
Just convert the number to String and call the method on it.
var number = 2;
var numberInString = number.toString();
var code = numberInString.charCodeAt(0);
console.log(code);

Replace any number with a specific number from variable

I have link like this foo.net/index.php?page=15
And I need to replace any number after page=xxx and get the new number from variable
This my current code just replace 15 to 16
var num = 16,
// What if the str = foo.net/index.php?page=10
str = 'foo.net/index.php?page=15',
n = str.replace('15',num);
$('span').html(n);
You can check the code in http://jsfiddle.net/KMsv7/
If you want to select and replace numbers in a string you can use regular expression:
// Replacing macting number with the specified value
var n = str.replace(/\d+/, num);
In case that you want to add/subtract/divide/multiply the matching value, you can also use the callback function of the .replace() method:
var n = str.replace(/\d+/, function(number) {
return number + 1;
});
Reference.

JavaScript: How to convert an HTML string into a JavaScript number?

I have a number that I need to pull from my html:
<span>123,456.78</span>
How can I convert this string into a number that I can do math on?
var numberString = $('span').text();
var realNumber = Number(numberString); //returns NaN
A jQuery-only solution would be okay.
parseInt() or parseFloat() would just about do it.
var number = parseFloat($('span').text());
after checking and seeing this doesn't work...
try
var number =
$('span').text().replace(/([^0-9\.])/g,"");
var number = parseFloat($('span').text().replace(/([^0-9\\.])/g,""));
I'm not sure what realNumber does, but here's how I'd convert that string into a number:
var numberString = $('span').text();
var amount = + numberString.replace(/,/g, '');
This removes the commas, then uses the + unary operator to convert the string to a number. In your example, the result is the number 123456.78.
updated
var numberString = $('span').text();
var number = Number(numberString.replace(/[^0-9\.]+/g,""));

Categories

Resources