Formatting number like 22,55,86,21,28 [duplicate] - javascript

This question already has answers here:
How can I convert a comma-separated string to an array?
(19 answers)
Closed 9 years ago.
I need to know how i can use javascript to separate a string like 22,44,85,63,12 to individual numbers without the commas e.g.:
22
44
85
63
12

var a = "one,two,three".split(",") // Delimiter is a string
for (var i = 0; i < a.length; i++)
{
alert(a[i])
}

You need the .split() method like this:
var str = "22,44,85,63,12";
var res = str.split(",");
res will then be a array of your numbers.
Here is a Fiddle

Use the split and join methods
var csv = '22,44,85,63,12';
var ssv = csv.split(',').join(' ');

First split the strings -
var str = ' 22,44,85,63,12';
var arr = str.split(',');
Then create an array of numbers. Check if the element is a number first though.
var numberArr = new Array();
var number;
for(var i = 0; i < arr.length; ++i)
{
number = parseInt(arr[i], 10);
if(!isNaN(number ))
{
numberArray.push(number);
}
}

Try -
var commaSepStr = "22,44,85,63,12";
var spaceSepStr = commaSepStr.replace(/,/g,' ');
This does a global replace. From what i understood, you want the output to be a string and not an array.

Use .split() for extracting the array of number-strings, and .map() for converting those number-strings to Number:
var str = "22,44,85,63,12";
var numbers = str.split(",").map(Number); //[22,44,85,63,12]

If you just want to replace the commas with a blank space how about using
string.replace(/,/g,' ');
but if you want them as separate integers then use var nums = string.split (",");

Related

Select 2 characters after a particular substring in javascript

We have a string ,
var str = "Name=XYZ;State=TX;Phone=9422323233";
Here in the above string we need to fetch only the State value i.e TX. That is 2 characters after the substring State=
Can anyone help me implement it in javascript.
.split() the string into array and then find the index of the array element having State string. Using that index get to that element and again .split() it and get the result. Try this way,
var str = "Name=XYZ;State=TX;Phone=9422323233";
var strArr = str.split(';');
var index = 0;
for(var i = 0; i < strArr.length; i++){
if(strArr[i].match("State")){
index = i;
}
}
console.log(strArr[index].split('=')[1]);
jsFiddle
I guess the easiest way out is by slicing and splitting
var str = "Name=XYZ;State=TX;Phone=9422323233";
var findme = str.split(';')[1];
var last2 = findme.slice(-2);
alert(last2);
Need more help? Let me know
indexOf returns the position of the string in the other string.
Using this index you can find the next two characters
javascript something like
var n = str.indexOf("State=");
then use slice method
like
var res = str.slice(n,n+2);
another method is :
use split function
var newstring=str.split("State=");
then
var result=newstring.substr(0, 2);
Check this:
var str1 = "Name=XYZ;State=TX;Phone=9422323233";
var n = str1.search("State");
n=n+6;
var res = str1.substr(n, 2);
The result is in the variable res, no matter where State is in the original string.
There are any number of ways to get what you're after:
var str = "Name=XYZ;State=TX;Phone=9422323233"
Using match:
var match = str.match(/State=.{2}/);
var state = match? match[0].substring(6) : '';
console.log(state);
Using replace:
var state = str.replace(/^.*State=/,'').substring(0,2);
console.log(state);
Using split:
console.log(str.split('State=')[1].substring(0,2));
There are many other ways, including constructing an object that has name/value pairs:
var obj = {};
var b = str.split(';');
var c;
for (var i=b.length; i; ) {
c = b[--i].split('=');
obj[c[0]] = c[1];
}
console.log(obj.State);
Take your pick.

Splitting a number into an array

Alright so I'm trying to completely split a number into an Array. So for example:
var num = 55534;
var arr = []; <- I would want the Array to look like this [5,5,5,3,4]
Basically i want to to completely split the number apart and place each Number into its own element of the array. Usually in the past i would just convert the number into a string then use the .split() function. This is how i use to do it:
num += "";
var arr = num.split("");
But this time i actually need to use these numbers, so they can not be strings. What would you guys say be the way of doing this?
Update, after the edit for some reason my code is crashing every run:
function DashInsert(num) {
num += "";
var arr = num.split("").map(Number); // [9,9,9,4,6]
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 === 1){
arr.splice(i,0,"-");
}// odd
}
return arr.join("");
}
String(55534).split("").map(Number)
...will handily do your trick.
You can do what you already did, and map a number back:
55534..toString().split('').map(Number)
//^ [5,5,5,3,4]
I'll do it like bellow
var num = 55534;
var arr = num.toString().split(''); //convert string to number & split by ''
var digits = arr.map(function(el){return +el}) //convert each digit to numbers
console.log(digits); //prints [5, 5, 5, 3, 4]
Basically I'm converting each string into numbers, you can just pass Number function into map also.

Java Script - Extract number from string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How might I extract the number from a number + unit of measure string using JavaScript?
How to extract number from string like this in JS.
String: "Some_text_123_text" -> 123
JSFiddle Demo
var s = "Some_text_123_text";
var index = s.match(/\d+/);
document.writeln(index);​
try this
var string = "Some_text_123_text";
var find = string.split("_");
for(var i = 0; i < find.length ; i ++){
if(!isNaN(Number(find[i]))){
var num = find[i];
}
}
alert(num);
try this working fiddle
var str = "Some_text_123_text";
var patt1 = /[0-9]/g;
var arr= str.match(patt1);
var myval = arr.join("");

how to make string as array in java script?

I have a string value like:
1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i
I need to convert it into array in JavaScript like
1 2 3
4 5 6
7 8 9
etc.
Can any one please suggest me a way how to do this?
You are looking for String.split. In your case, you need to split twice. Once with ; to split the string into chunks, then separately split each chunk with , to reach the array structure you are looking for.
function chunkSplit(str) {
var chunks = str.split(';'), // split str on ';'
nChunks = chunks.length,
n = 0;
for (; n < nChunks; ++n) {
chunks[n] = chunks[n].split(','); // split each chunk with ','
}
return chunks;
}
var arr = chunkSplit("1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i");
If you need a multi-dimensional array you can try :
var array = yourString.split(';');
var arrCount = array.length;
for (var i = 0; i < arrCount; i++)
{
array[i] = array[i].split(',');
}
Try the following:
var yourString = '1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var array = [];
yourString.split(';').forEach(function(value) {
array.push(value.split(','));
});
jsFiddle Demo
Note: .forEach() not supported in IE <=8
The following split command should help:
yourArray = yourString.split(";");

Javascript array from string of numbers

I am trying to work with arrays in javascript. Consider the following code:
var visList = '1234,5678,9'
var visListArray = new Array(visList);
for (i = 0; i <= visListArray.length - 1; i++)
{
alert(visListArray[i]);
}
Why doesn't this split the array into individual numbers instead of all of them clumped together?
Any help would be really appreciated.
Many thanks
Create the array by calling split() on the string:
var visList = '1234,5678,9'
var visListArray = visList.split(",");
You cannot substitue a string that looks like code for actual code. While this would work:
var visListArray = new Array(1234,5678,9);
Yours doesn't because the string is not interpreted by the Array constructor as 3 comma separated arguments, it is interpreted as one string.
Edit: Note that calling split() on a string results in an Array of strings. If you want an Array of numbers, you'll need to iterate the Array converting each string to a number. One convenient way to do that is to use the map() method:
visListArray = visList.split(",").map(function (item) {
return +item;
});
See the compatibility note for using map() in older browsers.
because its an string, try this:
var visList = '1234,5678,9'
var visListArray = [].concat(visList.split(','));
for (i = 0; i <= visListArray.length - 1; i++) {
alert(visListArray[i]);
}
You have to use string.split
var visList = '1234,5678,9'
var visListArray = visList.split(",");
for (i = 0; i <= visListArray.length - 1; i++)
{
alert(visListArray[i]);
}
To convert a symbol-separated list into an array, you may use split(symbol):
var list = "1221,2323,4554,7667".split(",");
for (var i = 0, il = list.length; i < il; i++) {
alert( +list[i] ); // a casting from string to number
}

Categories

Resources