javascript - string numbers - convert from 123,456 to 123456 - javascript

I have an array of string numbers like the follow:
"123,556","552,255,242","2,601","242","2","4"
and I would like to convert them to int numbers but the numbers with the "," I would like to convert from "123,556" to "123556" first.
How do I do so ?

var numbersArray = ["153,32","32,453,23","45,21"];
for (var i = 0; i < numbersArray.length; i++) {
numbersArray[i] = parseInt(numbersArray[i].replace(',',''));
}

var str = "552,255,242";
var numbr = parseInt(str.replace(/\,/g,''), 10);

You could use .replace method.
"123,556".replace(/,/g, '');

Try this: string.replace(',', '');

something like
var parseMe(myarray) {
var out = new Array(myarray.length);
for (i=0;i<myarray.length;i++){
var tokens[] = myarray[i].split(",");
var s = tokens[0] + tokens[1];
out.push(parseInt(s));
}
return out;
}

just use split, join (or replace) to remove the , and parseInt afterwards:
var number = "123,456";
number = number.split(',').join('');
number = parseInt(number, 10);

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;
}

How to split a number after n digits in javascript?

I have a number 2802 which is stored as a string in the backend. I want to split this number into 2 parts as 28 and 02 which should be shown as date 28/02? How can I do it with '/' in between them?
Try this : you can use substring as shown below. substring used for getting string between start index and end index. In your case, get string from 0 to 1 and then 2 to 3.
var str = "2802";
str = str.substring(0,2) + "/" + str.substring(2,4);
alert(str);
More information on Substring
Solution with regex
var res = "2802".match(/\d{2}/g).join('/');
document.write(res);
Are you asking about simple string manipulation?
var str = "1234";
var res = str.substr(0, 2)+"/"+str.substr(2,4);
You can do this:
var str = "2802";
str = str.split('').map(function(el, i){
if(i == 2){ el = '/'+el}
return el;
});
document.querySelector('pre').innerHTML = str.join('');
<pre></pre>
With regular expression:
var str = "2802";
str = str.replace(/(.{1,2}$)/gi, '/$1');
document.querySelector('pre').innerHTML = str;
<pre></pre>
var str = "2802";
var output = [str.slice(0, 2), str.slice(2)].join('/');
In this context conside 2802, 28 is date and 02 is month
Here 112, 028 what is date and month ?
A more generic solution could be
var num = 2802;
var output = String(num).match(new RegExp('.{1,2}', 'g')).join("/");
replace 2 with which ever number to split the number after n digits.
var n = 2;
var output = String(num).match(new RegExp('.{1,'+n+'}', 'g'));
var db_date = '112';
var date_str = '';
if(db_date.slice(0,1)==0){
var date_val = db_date.slice(0,2);
var month_val = db_date.slice(2,3);
if(month_val<=9){
month_val = '0'+month_val;
}
}else{
var date_val = db_date.slice(0,1);
date_val = parseInt(date_val);
if(date_val<=9){
date_val = date_val.toString();
date_val = '0'+date_val;
}
var month_val = db_date.slice(1,3);
}
alert(date_val+'/'+month_val);

JavaScript Split, Split string by last DOT "."

JavaScript Split,
str = '123.2345.34' ,
expected output 123.2345 and 34
Str = 123,23.34.23
expected output 123,23.34 and 23
Goal : JS function to Split a string based on dot(from last) in O(n).
There may be n number of ,.(commas or dots) in string.
In order to split a string matching only the last character like described you need to use regex "lookahead".
This simple example works for your case:
var array = '123.2345.34'.split(/\.(?=[^\.]+$)/);
console.log(array);
Example with destructuring assignment (Ecmascript 2015)
const input = 'jquery.somePlugin.v1.6.3.js';
const [pluginName, fileExtension] = input.split(/\.(?=[^\.]+$)/);
console.log(pluginName, fileExtension);
However using either slice or substring with lastIndexOf also works, and albeit less elegant it's much faster:
var input = 'jquery.somePlugin.v1.6.3.js';
var period = input.lastIndexOf('.');
var pluginName = input.substring(0, period);
var fileExtension = input.substring(period + 1);
console.log(pluginName, fileExtension);
var str = "filename.to.split.pdf"
var arr = str.split("."); // Split the string using dot as separator
var lastVal = arr.pop(); // Get last element
var firstVal = arr.join("."); // Re-join the remaining substrings, using dot as separator
console.log(firstVal + " and " + lastVal); //Printing result
I will try something like bellow
var splitByLastDot = function(text) {
var index = text.lastIndexOf('.');
return [text.slice(0, index), text.slice(index + 1)]
}
console.log(splitByLastDot('123.2345.34'))
console.log(splitByLastDot('123,23.34.23'))
I came up with this:
var str = '123,23.34.23';
var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
document.getElementById('output').innerHTML = JSON.stringify(result);
<div id="output"></div>
let returnFileIndex = str =>
str.split('.').pop();
Try this:
var str = '123.2345.34',
arr = str.split('.'),
output = arr.pop();
str = arr.join('.');
var test = 'filename.....png';
var lastStr = test.lastIndexOf(".");
var str = test.substring(lastStr + 1);
console.log(str);
I'm typically using this code and this works fine for me.
Jquery:
var afterDot = value.substr(value.lastIndexOf('_') + 1);
console.log(afterDot);
Javascript:
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Note: Replace quoted string to your own need
My own version:
var mySplit;
var str1;
var str2;
$(function(){
mySplit = function(myString){
var lastPoint = myString.lastIndexOf(".");
str1 = myString.substring(0, lastPoint);
str2 = myString.substring(lastPoint + 1);
}
mySplit('123,23.34.23');
console.log(str1);
console.log(str2);
});
Working fiddle: https://jsfiddle.net/robertrozas/no01uya0/
Str = '123,23.34.23';
var a = Str.substring(0, Str.lastIndexOf(".")) //123,23.34
var b = Str.substring(Str.lastIndexOf(".")) //23
Try this solution.
Simple Spilt logic
<script type="text/javascript">
var str = "123,23.34.23";
var str_array = str.split(".");
for (var i=0;i<str_array.length;i++)
{
if (i == (str_array.length-1))
{
alert(str_array[i]);
}
}
</script>
The simplest way is mentioned below, you will get pdf as the output:
var str = "http://somedomain.com/dir/sd/test.pdf";
var ext = str.split('.')[str.split('.').length-1];
Output: pdf

How to get a numeric value from a string in javascript?

Can anybody tell me how can i get a numeric value from a string containing integer value and characters?
For example,I want to get 45 from
var str="adsd45";
If your string is ugly like "adsdsd45" you can use regex.
var s = 'adsdsd45';
var result = s.match(/([0-9]+)/g);
['45'] // the result, or empty array if not found
You can use regular expression.
var regexp = /\d+/;
var str = "this is string and 989898";
alert (str.match(regexp));
Try this out,
var xText = "asdasd213123asd";
var xArray = xText.split("");
var xResult ="";
for(var i=0;i< xArray.length - 1; i++)
{
if(! isNan(xArray[i])) { xResult += xArray[i]; }
}
alert(+xResult);
var str = "4039";
var num = parseInt(str, 10);
//or:
var num2 = Number(str);
//or: (when string is empty or haven't any digits return 0 instead NaN)
var num3 = ~~str;
var strWithChars = "abc123def";
var num4 = Number(strWithChars.replace(/[^0-9]/,''));

how to parse string to int in 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

Categories

Resources