split an array string (split is not working) in javascript - javascript

I have an array like ["one, two, three"].
I want to convert it to ["one","two","three"].
I was using split to do this like:
$var temp=["one, two, three"];
temp.split(", ");
This is giving me error. Any idea how to do this?

It's an array with one single value, and you'd access that with [0] to get the string
var temp = ["one, two, three"];
var arr = temp[0].split(", ");
seems easier to just drop the brackets
var arr = "one, two, three".split(', ');
or write it as an array to begin with ?

["one, two, three"].pop().split(", ")

var temp=["one, two, three"];
temp[0].split(", ")

Related

How to get the string just before specific character in JavaScript?

I have couple of strings like this:
Mar18L7
Oct13H0L7
I need to grab the string like:
Mar18
Oct13H0
Could any one please help on this using JavaScript? How can I split the string at the particular character?
Many Thanks in advance.
For var str = 'Mar18L7';
Try any of these:
str.substr(0, str.indexOf('L7'));
str.split('L7')[0]
str.slice(0, str.indexOf('L7'))
str.replace('L7', '')
Based on input that is given it I have created following function which can take n string in array and return the output in the format you have given. Check if this helps and if some use case is missed.
function generateStr(arr, splitStr) {
const processedStr = arr.map(value => value.split(splitStr)[0]);
return processedStr.join(" OR ");
}
console.log(generateStr(["Mar18L7", "Oct13H0L7"], "L7"));
You can use a regex like this
var data = ["Mar18L7", "Oct13H0L7"];
var regex = /^([a-zA-Z0-9]+)\L[a-zA-Z0-9]+$/;
var output = []
data.forEach(function(el){
var matches = el.match(regex);
output.push(matches[1]);
});
output variable will be equal to ['Mar18', 'Oct13H0'] and you can join all value usin the .join method on output array
var chain = output.join(" OR ");
// chain will be equal to "Mar18 OR Oct13H0"

String to array node js javascript

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?
Because they have '\n' in-between, use split()
let arr = str.split('\n')
console.log(arr[0]);
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]);
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]);
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.
array.split(/\n/)
or
array.split(\n)

Split square brackets into commas, remove first and last comma

I have written the following console log to convert a list of [] to commas:
[Item 1][Item 2][Item 3][Item 4]
...
.split(/[[\]]{1,2}/);
but I am getting the following printed out:
,Item 1,Item 2,Item 3,Item 4,
when I am looking for:
Item 1,Item 2,Item 3,Item 4
I have tried a variety of different approaches but none provide me with the above last result.
You could use match instead of split and take directly the result array.
var string = '[Item 1][Item 2][Item 3][Item 4]',
parts = string.match(/[^\[\]]+/g);
console.log(parts);
Without going with regex, you could just slice it before splitting.
var str = "[Item 1][Item 2][Item 3][Item 4]";
var result = str.slice(1,-1).split`][`;
console.log(result);
The regex option would be:
var str = "[Item 1][Item 2][Item 3][Item 4]";
var result = str.match(/[\w ]+/g);
console.log(result);

Convert a string of array into array javascript

In my code i am reading a hidden input value which is actually a javascript array object
<input type="hidden" id="id_num" value="{{array_values}}">
But when i taking it using jquery ($('#id_num").val()) its a string of array,
"['item1','item2','item3']"
so i can not iterate it.How should i convert into javascript array object, so that i can iterate through items in the array?
You can use JSON.parse but first you need to replace all ' with " as ' are invalid delimitters in JSON strings.
var str = "['item1','item2','item3']";
str = str.replace(/'/g, '"');
var arr = JSON.parse(str);
console.log(arr);
Another approach:
Using slice and split like this:
var str = "['item1','item2','item3']";
var arr = str.slice(1, -1) // remove [ and ]
.split(',') // this could cause trouble if the strings contain commas
.map(s => s.slice(1, -1)); // remove ' and '
console.log(arr);
You can use eval command to get values from string;
eval("[0,1,2]")
will return;
[0,1,2]
more details here
Though it should be noted, if this string value comes from users, they might inject code that would cause an issue for your structure, if this string value comes only from your logic, than it is alright to utilize eval
var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
A possible way of solving this:
First, substr it to remove the [..]s.
Next, remove internal quotes, since we would be getting extra when we string.split
Finally, split with ,.
let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
.replace(/'/g, "")
.split(",")
console.log(arr)

Count the elements in string

I have a string that has comma separated values. How can I count how many elements in the string separated by comma?
e.g following string has 4 elements
string = "1,2,3,4";
myString.split(',').length
var mystring = "1,2,3,4";
var elements = mystring.split(',');
return elements.length;
All of the answers suggesting something equivalent to myString.split(',').length could lead to incorrect results because:
"".split(',').length == 1
An empty string is not what you may want to consider a list of 1 item.
A more intuitive, yet still succinct implementation would be:
myString.split(',').filter((i) => i.length).length
This doesn't consider 0-character strings as elements in the list.
"".split(',').filter((i) => i.length).length
0
"1".split(',').filter((i) => i.length).length
1
"1,2,3".split(',').filter((i) => i.length).length
3
",,,,,".split(',').filter((i) => i.length).length
0
First split it, and then count the items in the array. Like this:
"1,2,3,4".split(/,/).length;
First You need to convert the string to an array using split, then get the length of the array as a count, Desired Code here.
var string = "1,2,3,4";
var desiredCount = string.split(',').length;

Categories