String to array node js javascript

3.14159265432 Source

Hi my current string is shown:

082759
078982
074470
066839
062069
062068
062029
062027
059304
059299
056449
056421
052458
050666
100530
078977
072967
072958
072957
066982
062864
062064
056506
052456

24 6 digit numbers in total, notice the new lines between them. I need this entire string to be broken down into an array such that [082759,078982,etc] is displayed and so that when calling:

console.log(array[0])

will output:

082759

NOTE: The '\n' method does not seem to work and when re-calling it [when within an array], e.g array[0], it outputs all the numbers.

The variable under which this data is derived from comes via:

var currentSku = $(this).attr('data-productsku')

So if this j-query has a specific string type then its probably something to do with this?

javascriptarraysstring

Answers

answered 3 months ago Whatever #1

Because they have '\n' in-between, use split()

let arr = str.split('\n')
console.log(arr[0]);

answered 3 months ago kartik chawla #2

array.split(/\n/)

or

array.split(\n)

answered 3 months ago Raaj Nadar #3

Try this code

var test = "082759 078982 074470 066839 062069 062068";

var arr = test.split(" ");
console.log(arr[0]);
console.log(arr[4]);

Tested code!

Note: There should be a space in between each number.

Next line solution is here

var test = 
`082759
078982
074470
066839
062069
06206`;

var arr = test.split("\n");
console.log(arr[0]);
console.log(arr[4]);

answered 3 months ago Alex #4

If you're adding the digit on a new-line each time, you can use .split() method.

You have to pass the delimiter you want to split by; in your case, you use \n as that's how new-lines are escaped in Javascript. This will create an array of data.

Using the code below you can do like so:


let string = `082759
078982
074470
066839
062069
062068
062029
062027
059304
059299
056449
056421
052458
050666
100530
078977
072967
072958
072957
066982
062864
062064
056506
052456`;

let arr = string.split('\n');

console.log(arr[0]);

answered 3 months ago Musa #5

If splitting using \n doesn't work then it might be that your string is using a different style of line ending. You can try \r or \r\n for instance.

comments powered by Disqus