String split returns an array with more elements than expected (empty elements) - javascript

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

Related

javascript split string function not working

I am trying to split a string:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = device_data.split('*');
But it's not working. it's just displaying this string
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = str.split('*');
console.dir(res)
,HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#,HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555
Instead of creating an array with two elements.
IMHO, you want something like this:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
splitStrArr = str.split('*').filter(str => str != "")
console.log(splitStrArr)
console.log(splitStrArr[0])
console.log(splitStrArr[1])
You are getting a string with a period in the beginning because whatever you are doing leads to the result of String#split being converted to a string. String#split returns an array. An array converted to a string is of the form of element0,element1,element2 ... elements separated by commas.
The result of String#split in your case is ["",...] with 3 elements since your string begins with the character '*' you are searching, so String#split will create an empty string as the first element of the returned array. So the result is exactly as expected, and String#split is working as intended.
get rid of the first character of the string,
mystring.substr(1).split('*')
get rid of the empty strings
mystring.split('*').filter(s=>s!='')
to obtain the desired result.
You can use:
var res = str.split("#");
You can check in Javascript console in browser itself.
As a suggestion/ idea, you can always use the browser console, for example, Chrome browser, to execute simple scripts like these.
This way, you can save time, as it is easier to check your data structures, their internal data.
If you try
var res = str.split('*');
you obtain three elements:
res[0] is '' (empty string)
res[1] is 'HQ,61...'
res[2] is 'HQ,...'

Extract Twitter handlers from string using regex in JavaScript

I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");

Javascript to cut same second character on a text

For example I have text:
var x="default_1305, default_1695, default_1805";
I want to cut before the second comma to get this text:"default_1305, default_1695".
How can I do this?
var x="default_1305, default_1695, default_1805";
string can be split by , like below:
var res = x.split(",", 2);
Note 2 here in the second param.
And if needed as string, then
var res_string = res.join(",");
Edit:
.split() on MDN
Syntax
str.split([separator[, limit]])
Parameters
separator
Optional. Specifies the character(s) to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.
limit
Optional. Integer specifying a limit on the number of splits to be found. The split() method still splits on every match of separator, until the number of split items match the limit or the string falls short of separator.
Convert string to array and get first two elements
var x="default_1305, default_1695, default_1805";
var b = x.split(',')
var c = b[0]+","+b[1]
You can also use .slice() to get the parts you need, eg:
// added an extra item to distinguish first-two vs all-but-last
var x="default_1305, default_1695, default_1805, default_1962";
// get first two
var result = x.split(",").slice(0,2).join(",");
console.log(result);
// get all but last
var result = x.split(",").slice(0,-1).join(",");
console.log(result);

String to array select only elements with a length of 6

Lets suppose i have this string:
01234 ; 0123;0424 09234
How can i split these string by two arguments ' ' and ';',
Trim the single elements
and next, select only these elements of the array who have a length of 5
So that at the end it returns this array:
["01234","09234"]
My biggest problem with this task is that i dont know how i should split the string because always when i do:
a = "0123 9809; 04323 ";
b = a.split(' ').split(';')
I get this error:
TypeError: Object [object Array] has no method 'split'
Thanks for your help!
Use:
' 01234 ; 0123;0424 09234'.split(/\s|;/).filter(function (e) {
return e.trim().length === 5;
});
in the example above split accepts a regular expression used for splitting the string. After that we use the high-order function filter, which filters the input.
The is valid for all modern browsers.
.split() works on strings so that is why you are seeing the error - you are calling it on a string which returns an array, and they trying to call it again on the array. There are many ways to approach this.
I'd be tempted to take a short cut and replace all spaces with semicolons and then perform a single .split(';') to generate the array, and then use .filter() to filter out only those strings in the array that match the length you are looking for.

Regular Expression to get the last word from TitleCase, camelCase

I'm trying to split a TitleCase (or camelCase) string into precisely two parts using javascript. I know I can split it into multiple parts by using the lookahead:
"StringToSplit".split(/(?=[A-Z])/);
And it will make an array ['String', 'To', 'Split']
But what I need is to break it into precisely TWO parts, to produce an array like this:
['StringTo', 'Split']
Where the second element is always the last word in the TitleCase, and the first element is everything else that precedes it.
Is this what you are looking for ?
"StringToSplit".split(/(?=[A-Z][a-z]+$)/); // ["StringTo", "Split"]
Improved based on lolol answer :
"StringToSplit".split(/(?=[A-Z][^A-Z]+$)/); // ["StringTo", "Split"]
Use it like this:
s = "StringToSplit";
last = s.replace(/^.*?([A-Z][a-z]+)(?=$)/, '$1'); // Split
first = s.replace(last, ''); // StringTo
tok = [first, last]; // ["StringTo", "Split"]
You could use
(function(){
return [this.slice(0,this.length-1).join(''), this[this.length-1]];
}).call("StringToSplit".split(/(?=[A-Z])/));
//=> ["StringTo", "Split"]
In [other] words:
create the Array using split from a String
join a slice of that Array without the last element of that
Array
add that and the last element to a final Array

Categories

Resources