.split() JS not "splitting" correctly? - javascript

I've got the following string:
str = "data1 data2 data3";
And I want to convert it to an array doing the following:
list = str.split(",");
But when I run this:
alert(list[1]);
…it does not retrieve "data2". And when I call this:
alert(data[0]);
¬it retrieves "data1, data2, data3".
Is there something wrong? I want to access the different words from the string by calling them from the number (0,1,2 - in this case) instead of all of them going to list[0]

The separator you are using in the split method is comma(,). But your input string does not have a comma, but it has spaces between words. So you need to split with space as the operator.
list = str.split(" ");
When separator is found, it is removed from the string and the substrings are returned in an array. If separator is not found, the array contains one element consisting of the entire string.

You are trying to split using "," as a separator. You will have to use:
list = str.split(" ");
It'll work that way ;)

Related

Why is the first match empty when using a split regex? [duplicate]

I don't understand this behaviour:
var string = 'a,b,c,d,e:10.';
var array = string.split ('.');
I expect this:
console.log (array); // ['a,b,c,d,e:10']
console.log (array.length); // 1
but I get this:
console.log (array); // ['a,b,c,d,e:10', '']
console.log (array.length); // 2
Why two elements are returned instead of one? How does split work?
Is there another way to do this?
You could add a filter to exclude the empty string.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(function(el) {return el.length != 0});
A slightly easier version of #xdazz version for excluding empty strings (using ES6 arrow function):
var array = string.split('.').filter(x => x);
This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.
If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Use String.split() method with Array.filter() method.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(item => item);
console.log(array); // [a,b,c,d,e:10]
console.log (array.length); // 1
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
trim the trailing period first
'a,b,c,d,e:10.'.replace(/\.$/g,''); // gives "a,b,c,d,e:10"
then split the string
var array = 'a,b,c,d,e:10.'.replace(/\.$/g,'').split('.');
console.log (array.length); // 1
That's because the string ends with the . character - the second item of the array is empty.
If the string won't contain . at all, you will have the desired one item array.
The split() method works like this as far as I can explain in simple words:
Look for the given string to split by in the given string. If not found, return one item array with the whole string.
If found, iterate over the given string taking the characters between each two occurrences of the string to split by.
In case the given string starts with the string to split by, the first item of the result array will be empty.
In case the given string ends with the string to split by, the last item of the result array will be empty.
It's explained more technically here, it's pretty much the same for all browsers.
According to MDN web docs:
Note: When the string is empty, split() returns an array containing
one empty string, rather than an empty array. If the string and
separator are both empty strings, an empty array is returned.
const myString = '';
const splits = myString.split();
console.log(splits);
// ↪ [""]
Well, split does what it is made to do, it splits your string. Just that the second part of the split is empty.
Because your string is composed of 2 part :
1 : a,b,c,d,e:10
2 : empty
If you try without the dot at the end :
var string = 'a,b,c:10';
var array = string.split ('.');
output is :
["a,b,c:10"]
You have a string with one "." in it and when you use string.split('.') you receive array containing first element with the string content before "." character and the second element with the content of the string after the "." - which is in this case empty string.
So, this behavior is normal. What did you want to achieve by using this string.split?
try this
javascript gives two arrays by split function, then
var Val = "abc#gmail.com";
var mail = Val.split('#');
if(mail[0] && mail[1]) { alert('valid'); }
else { alert('Enter valid email id'); valid=0; }
if both array contains length greater than 0 then condition will true

Split and grab text before second hyphen

I have the following text string:
test-shirt-print
I want to filter the text string so that it only returns me:
test-shirt
Meaning that everything that comes after the second hyphen should be removed including the hyphen.
I am thinking that the solution could be to split on hyphen and somehow select the two first values, and combine them again.
I am unaware of which functionality is best practice to use here, I also thinking that if it would be possible to use a regular expression in order to be able to select everything before the second hyphen.
You can use split slice and join together to remove everything after the second hyphen
var str = "test-shirt-print";
console.log(str.split("-").slice(0, 2).join('-'))
You can try with String.prototype.slice()
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
and String.prototype.lastIndexOf()
The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.
var str = 'test-shirt-print';
var res = str.slice(0, str.lastIndexOf('-'));
console.log(res);
You can also use split() to take the first two items and join them:
var str = 'test-shirt-print';
var res = str.split('-').slice(0,2).join('-');
console.log(res);

How to filter string "1M,3F,2M" to "1,3,2" through jquery?

I have String 2M,1F,5M,6F selected seats with gender. how to filter this string to only numbers with comma?
something like this,
stringVal.replace(/, /g, ",").replace(/,/g, ", ");
this one returns with space after comma but i want only numbers with comma.
Why not replace all alphabetical characters with the empty string?
const stringVal = '1M,3F,2M';
console.log(
stringVal.replace(/[a-z]/gi, '')
);
You can use split() on comma and then parseInt() each value of array to get the number and then join() it using comma.
var stringVal = '1M,3F,2M';
stringVal = stringVal.split(',').map(x=> parseInt(x)).join(',');
console.log(stringVal);
You can use this for getting numbers,
console.log('2M,1F,5M,6F'.replace(/[^\d,]+/g, ''));
I have String 2M,1F,5M,6F selected seats with gender
It seems the string contains M and F so you can replace those with empty string.
var stringVal = '2M,1F,5M,6F'
stringVal = stringVal.replace(/[MF]/g, "")
console.log(stringVal);
Here is an approach using split directly on the input string to generate an output array of values:
var input = "2M,1F,5M,6F";
input = input + ",";
var genders = input.split(/[A-Z],/);
genders.pop();
console.log(genders);
We add a trailing comma to the end of the input string, so that the split pattern will fire (and consume) the very last comma and gender code. But this produces an extra empty entry in the output array, which we then pop off.
The possible advantage of this approach might be if you needed to have these values in an array anyway, and you wanted to achieve this in a single step.

How to convert an array like string to array in node.js?

Actually I'm getting the arraylist from android device in node.js . But as it's in string form so I wanna convert it into an array . For that I've referred a lot of similar questions in SO but none of them were helpful . I also tried to use JSON.parse() but it was not helpful.
I'm getting societyList in form '[Art, Photography, Writing]'.Thus how to convert this format to an array?
Code:
var soc_arr=JSON.parse(data.societyList)
console.log(soc_arr.length)
use something like this
var array = arrayList.replace(/^\[|\]$/g, "").split(", ");
UPDATE:
After #drinchev suggestion regex used.
regex matches char starts with '[' and ends with ']'
This string is not valid JSON since it does not use the "" to indicate a string.
The best way would be to parse it yourself using a method like below:
let data = '[test1, test2, test3]';
let parts = data
.trim() // trim the initial data!
.substr(1,data.length-2) // remove the brackets from string
.split(',') // plit the string using the seperator ','
.map(e=>e.trim()) // trim the results to remove spaces at start and end
console.log(parts);
RegExp.match() maybe
console.log('[Art, Photography, Writing]'.match(/\w+/g))
So match() applies on any string and will split it into array elements.
Use replace and split. In addition, use trim() to remove the trailing and leading whitespaces from the array element.
var str = '[Art, Photography, Writing]';
var JSONData = str.replace('[','').replace(']','').split(',').map(x => x.trim());
console.log(JSONData);

Why is the comma-separated string not converting to an array using split() in javaScript?

I am trying to convert a comma separated string into an array using the split method(Convert comma separated string to array).
This is the code:
var nameList = "milk,sugar,flour";
var nameArray = nameList.split(',');
document.write('The nameList is: ' + nameList);
document.write('<br />');
document.write('The nameArray is: ' + nameArray);
This is the output:
The nameList is: milk,sugar,flour The nameArray is:
milk,sugar,flour
It looks to me like it is still a string separated by commas. Why is the comma-separated string not converting to an array using split() in javaScript?
It's an array. Array#toString produces the comma-separated output.
Try this:
[3, 4, 'b'].toString();
If you use console.log instead of document.write to inspect nameArray, you'll see that it is an array.
thats the way how JAVASCRIPT shoes an array
it did convert it
but you told JS to display it
so thats what he does.
proof:
nameArray[0]====>milk
nameArray[1]====>sugar
When you implicitly convert the array to a string by appending it to a string, it displays the array.toString() which uses commas. You can override this if you want.
if you do this instead, it will show the properly annotated version.
JSON.stringify( nameArray ,"\t")

Categories