how to parse string to int in javascript - javascript

i want int from string in javascript how i can get them from
test1 , stsfdf233, fdfk323,
are anyone show me the method to get the integer from this string.
it is a rule that int is always in the back of the string.
how i can get the int who was at last in my string

var s = 'abc123';
var number = s.match(/\d+$/);
number = parseInt(number, 10);
The first step is a simple regular expression - \d+$ will match the digits near the end.
On the next step, we use parseInt on the string we've matched before, to get a proper number.

You can use a regex to extract the numbers in the string via String#match, and convert each of them to a number via parseInt:
var str, matches, index, num;
str = "test123and456";
matches = str.match(/\d+/g);
for (index = 0; index < matches.length; ++index) {
num = parseInt(matches[index], 10);
display("Digit series #" + index + " converts to " + num);
}
Live Example
If the numbers really occur only at the ends of the strings or you just want to convert the first set of digits you find, you can simplify a bit:
var str, matches, num;
str = "test123";
matches = str.match(/\d+/);
if (matches) {
num = parseInt(matches[0], 10);
display("Found match, converts to: " + num);
}
else {
display("No digits found");
}
Live example
If you want to ignore digits that aren't at the end, add $ to the end of the regex:
matches = str.match(/\d+$/);
Live example

var str = "stsfdf233";
var num = parseInt(str.replace(/\D/g, ''), 10);

var match = "stsfdf233".match(/\d+$/);
var result = 0; // default value
if(match != null) {
result = parseInt(match[0], 10);
}

Yet another alternative, this time without any replace or Regular Expression, just one simple loop:
function ExtractInteger(sValue)
{
var sDigits = "";
for (var i = sValue.length - 1; i >= 0; i--)
{
var c = sValue.charAt(i);
if (c < "0" || c > "9")
break;
sDigits = c + sDigits;
}
return (sDigits.length > 0) ? parseInt(sDigits, 10) : NaN;
}
Usage example:
var s = "stsfdf233";
var n = ExtractInteger(s);
alert(n);

This might help you
var str = 'abc123';
var number = str.match(/\d/g).join("");

Use my extension to String class :
String.prototype.toInt=function(){
return parseInt(this.replace(/\D/g, ''),10);
}
Then :
"ddfdsf121iu".toInt();
Will return an integer : 121

First positive or negative number:
"foo-22bar11".match(/-?\d+/); // -22

javascript:alert('stsfdf233'.match(/\d+$/)[0])
Global.parseInt with radix is overkill here, regexp extracted decimal digits already and rigth trimmed string

Related

How to make a single string into a multitude of strings?

I have a string called e3 which holds the string 1,2,4,5,3,6. I want to add up all of those numbers up to make the number 21 I was considering doing a for loop for this however I do not know how to turn part of a string into its own value.
I anyone has any better idea of what to do please comment, or answer.
You could use String#split for the string and use Array#reduce for summing.
var e3 = '1,2,4,5,3,6',
sum = e3.split(',').reduce(function (a, b) {
return a + +b; // +b forces b to number
}, 0);
console.log(sum);
If you are sure that it is always a comma separated list of numbers, you could split it on the comma into an array and then use array.reduce() to sum them
var asString = '1,2,4,5,3,6';
var asArray = asString.split(',');
var total = asArray.reduce(function(prev, current){
return prev + parseInt(current, 10);
}, 0);
console.log(total) // outputs 21;
You can do it like this:
var e3 = "1,2,4,5,3,6";
// Split by separator ','
var stringsArr = e3.split(',');
var sum = 0;
// Loop through array of string numbers
stringsArr.forEach(function(str) {
// get Int from a string
var strVal = parseInt(str, 10);
sum += strVal;
});
here's the fiddle
Here is working code to do what you need: https://plnkr.co/edit/8LSkZi0oC8msbHI0qOrz?p=preview
At first you use the split method - this separates a string into an array of strings, based on some separator value. In our case, the separator is a comma, but it could be a blank space or something else:
var testString = '1,2,4,5,3,6';
var separator = ',';
function splitStringOnCommasAndGetArray(string, separator){
var arrayOfStrings = string.split(separator);
return arrayOfStrings;
}
After that, we loop through the array and turn each value into a number. We add the numbers, like so:
function addUpArray(arrayOfStrings){
var totalNumber = 0;
for(var i = 0; i < arrayOfStrings.length; i++){
var currentNum = parseInt(arrayOfStrings[i]);
console.log(currentNum);
totalNumber += currentNum;
}
return totalNumber;
}

Wrap each digitand prepend zeros up to X digits

Is there a possibility to wrap each character in Javascript and prepend zero's if its less then X digits?
What i get/have:
var votes = 2;
//or
var votes = 123;
//or
var votes = 4321;
what it should to look like:
<span>0</span><span>0</span><span>0</span><span>2</span>
//or
<span>0</span><span>1</span><span>2</span><span>3</span>
//or
<span>4</span><span>3</span><span>2</span><span>1</span>
so the result should be a number with four digits.
here's a tricky version:
var votes = 123;
("0000" + votes).slice(-4); /* 0123 */
thus, to wrap each digit in a <span> you could fetch each digit with $.map and wrap it into its own element, like in this example fiddle: http://jsfiddle.net/cZAWj/
var votes = 973;
$.map(("0000" + votes).slice(-4), function(digit) {
$('<span/>', { text : digit }).appendTo($('body'));
});
Firstly, make it look like a string and pad it...
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Then you can iterate over it and add a span around each number. Then write the markup out as the .html of the parent element.
Well one way to do it would be to convert the number to a string and pre-append 0 until we reach the desired length.
So if you want X digits:
var strNb = "" + nb;
while (strNb.length < X){
strNb = "0" + strNb
}
function formatNumber(d, x) {
var l = String(d).length;
return (l<x?(Array(x-l).join('0') + d):String(d)).replace(/\d/g,"<span>$&</span>");
}

Remove/ truncate leading zeros by javascript/jquery

Suggest solution for removing or truncating leading zeros from number(any string) by javascript,jquery.
You can use a regular expression that matches zeroes at the beginning of the string:
s = s.replace(/^0+/, '');
I would use the Number() function:
var str = "00001";
str = Number(str).toString();
>> "1"
Or I would multiply my string by 1
var str = "00000000002346301625363";
str = (str * 1).toString();
>> "2346301625363"
Maybe a little late, but I want to add my 2 cents.
if your string ALWAYS represents a number, with possible leading zeros, you can simply cast the string to a number by using the '+' operator.
e.g.
x= "00005";
alert(typeof x); //"string"
alert(x);// "00005"
x = +x ; //or x= +"00005"; //do NOT confuse with x+=x, which will only concatenate the value
alert(typeof x); //number , voila!
alert(x); // 5 (as number)
if your string doesn't represent a number and you only need to remove the 0's use the other solutions, but if you only need them as number, this is the shortest way.
and FYI you can do the opposite, force numbers to act as strings if you concatenate an empty string to them, like:
x = 5;
alert(typeof x); //number
x = x+"";
alert(typeof x); //string
hope it helps somebody
Since you said "any string", I'm assuming this is a string you want to handle, too.
"00012 34 0000432 0035"
So, regex is the way to go:
var trimmed = s.replace(/\b0+/g, "");
And this will prevent loss of a "000000" value.
var trimmed = s.replace(/\b(0(?!\b))+/g, "")
You can see a working example here
parseInt(value) or parseFloat(value)
This will work nicely.
I got this solution for truncating leading zeros(number or any string) in javascript:
<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
return s;
}
var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';
alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>
Simply try to multiply by one as following:
"00123" * 1; // Get as number
"00123" * 1 + ""; // Get as string
1. The most explicit is to use parseInt():
parseInt(number, 10)
2. Another way is to use the + unary operator:
+number
3. You can also go the regular expression route, like this:
number.replace(/^0+/, '')
Try this,
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
var str =ltrim("01545878","0");
More here
You should use the "radix" parameter of the "parseInt" function :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FparseInt
parseInt('015', 10) => 15
if you don't use it, some javascript engine might use it as an octal
parseInt('015') => 0
If number is int use
"" + parseInt(str)
If the number is float use
"" + parseFloat(str)
const number = '0000007457841';
console.log(+number) //7457841;
OR number.replace(/^0+/, '')
Regex solution from Guffa, but leaving at least one character
"123".replace(/^0*(.+)/, '$1'); // 123
"012".replace(/^0*(.+)/, '$1'); // 12
"000".replace(/^0*(.+)/, '$1'); // 0
I wanted to remove all leading zeros for every sequence of digits in a string and to return 0 if the digit value equals to zero.
And I ended up doing so:
str = str.replace(/(0{1,}\d+)/, "removeLeadingZeros('$1')")
function removeLeadingZeros(string) {
if (string.length == 1) return string
if (string == 0) return 0
string = string.replace(/^0{1,}/, '');
return string
}
One another way without regex:
function trimLeadingZerosSubstr(str) {
var xLastChr = str.length - 1, xChrIdx = 0;
while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
xChrIdx++;
}
return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}
With short string it will be more faster than regex (jsperf)
const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;
Use "Math.abs"
eg: Math.abs(003) = 3;
console.log(Math.abs(003))

How can I parse a string in Javascript?

I have string looking like this:
01
02
03
99
I'd like to parse these to make them into strings like:
1. 2. 3. 99. etc.
The numbers are a maximum of 2 characters. Also I have to parse some more numbers later in the source string so I would like to learn the substring equivalent in javascript. Can someone give me advice on how I can do. Previously I had been doing it in C# with the following:
int.Parse(RowKey.Substring(0, 2)).ToString() + "."
Thanks
Why, parseInt of course.
// Add 2 until end of string
var originalA = "01020399";
for (var i = 0; i < originalA.length; i += 2)
{
document.write(parseInt(originalA.substr(i, 2), 10) + ". ");
}
// Split on carriage returns
var originalB = "01\n02\n03\n99";
var strArrayB = originalB.split("\n");
for (var i = 0; i < strArrayB.length; i++)
{
document.write(parseInt(strArrayB[i], 10) + ". ");
}
// Replace the leading zero with regular expressions
var originalC = "01\n02\n03\n99";
var strArrayC = originalC.split("\n");
var regExpC = /^0/;
for (var i = 0; i < strArrayC.length; i++)
{
document.write(strArrayC[i].replace(regExpC, "") + ". ");
}
The other notes are that JavaScript is weakly typed, so "a" + 1 returns "a1". Additionally, for substrings you can choose between substring(start, end) and substr(start, length). If you're just trying to pull a single character, "abcdefg"[2] will return "c" (zero-based index, so 2 means the third character). You usually won't have to worry about type-casting when it comes to simple numbers or letters.
http://jsfiddle.net/mbwt4/3/
use parseInt function.
parseInt(09) //this will give you 9
var myString = parseInt("09").toString()+". "+parseInt("08").toString();
string = '01\n02\n03\n99';
array = string.split('\n');
string2 = '';
for (i = 0; i < array.length; i++) {
array[i] = parseInt(array[i]);
string2 += array[i] + '. ';
}
document.write(string2);
var number = parseFloat('0099');
Demo
Substring in JavaScript works like this:
string.substring(from, to);
where from is inclusive and to is exclusive. You can also use slice:
string.slice(from, to)
where from is inclusive and to is exclusive. The difference between slice and substring is with slice you can specify negative numbers. For example, from = -1 indicates the last character. from(-1, -3) would give you the last 2 characters of the string.
With both methods if you don't specify end then you will get all the characters to the end.
Paul
Ii they are always 2 digits how about;
var s = "01020399";
var result = []
for (var i = 0; i < s.length; i+=2)
result.push(parseInt(s.substr(i, 2), 10) + ".")
alert( result[2] ) // 3.
alert( result.join(" ") ) // 1. 2. 3. 99.

How do i get numbers from this string?

i have this string:
var s = 'http://xxxxxxx.xxx/abcd123456789?abc=1';
how do i get digits 123456789 (between "d" and "?") ?
these digits may vary. the number of digits may vary as well.
How do i get them?? Regex? Which one?
try
'http://xxxxxxx.xxx/abcd123456789?abc=1'.match(/\d+(?=\?)/)[0];
// ^1 or more digits followed by '?'
Try
var regexp = /\/abcd(\d+)\?/;
var match = regexp.exec(input);
var number = +match[1];
Are the numbers always between "abcd" and "?"?
If so, then you can use substring():
s.substring(s.indexOf('abcd'), s.indexOf('?'))
If not, then you can just loop through character by character and check if it's numeric:
var num = '';
for (var i = 0; i < s.length; i++) {
var char = s.charAt(i);
if (!isNaN(char)) {
num += char;
}
}
Yes, regex is the right answer. You'll have something like this:
var s = 'http://xxxxxxx.xxx/abcd123456789?abc=1';
var re = new RegExp('http\:\/\/[^\/]+\/[^\d]*(\d+)\?');
re.exec(s);
var digits = $1;

Categories

Resources