How to use array.splice() after .join()? - javascript

I'm having trouble figuring out how to remove items from an array after using the join() function.
As you'll see, the first array.splice() works, but the second does not...
var recordsArray1 = ['a','b','c','d','e','f'];
console.log(recordsArray1.length);
recordsArray1.splice('a', 1);
console.log(recordsArray1);
var recordsArray2 = ['g','h','i','j','k','l'].join('\n');
console.log(recordsArray2.length);
recordsArray2.splice('g', 1);
console.log(recordsArray2);
Thanks for any help.
Tim

Array.prototype.join(separator) converts an array into a string seperated by separator. If you want to join the elements with a newline, perform the join after any other array operations, like slicing.

https://www.w3schools.com/jsref/jsref_join.asp
join turns it from an array into a string

If I understood your need correctly, you may want to map over the elements and add newline to each, instead of joining the array to a string. This should do:
recordsArray2 = ['g','h','i','j','k','l']
recordsArray2.map((x) => x + "\n")

First, your usage of splice is not right. Your intention seems to be "please, remove exactly one a" respectively "please remove a g". But that's not how splice works. The first parameter is the index to start at, the correct usage would be .splice(0, 1) (read: remove one element starting from index 0).
Second, join converts the Array to a string using the provided sequence. So, ['g','h','i','j','k','l'].join('\n'); yields g\nh\ni\n... as a string, which does not have a join method. So, to remove the g, I suggest to join the array after you removed the g: var arr =['g','h','i','j','k','l']; arr.splice(0, 1); arr = arr.join('\n'); (or do not join it after all, since I think it was not what you intended to do). Another way would to remove the G after joining, e.g. var arr =['g','h','i','j','k','l'].join('\n').substr(2) (which would return the string starting at the third character, so the g and the following \n are removed).

Related

Javascript selecting to save one index of split()

I have a value - toggle-save_2
I want to extract the 2 part. The part after the underscore will always be what i need but the length of the former part, which in this case is toggle-save_, may vary (eg. notoggle-val_45). Though this length may vary it will always be separated from the end number by an underscore.
Right now I am using this
var current = this.id.split('_');
current = current[1];
to select the number.
What would be cool is if I could pass a variable to the split to only give me the second index of the result from the split.
Just select the 2nd index when you do the split.
var current = this.id.split('_')[1];
The best solution here would be to use lastIndexOf and substring, like this
function getLastPart(strObject) {
return strObject.substring(strObject.lastIndexOf("_") + 1);
}
console.log(getLastPart("toggle-save_2"));
// 2
console.log(getLastPart("notoggle-save_45"));
// 45
It is better for this case because, you already know that the _ will be somewhere near the last position. Since lastIndexOf starts from the last position, it would find _ very soon and all we need to do is to get the rest of the string from the next position.
There are often times I am breaking up a string where I only need the very last value of the result of String.prototype.split and consider the rest to be garbage no matter how many values the split produced.
When those cases arise, I like to chain Array.prototype.pop off of the split
var s = 'toggle-save_2',
current = s.split('_').pop();
The split method can only be limited from the end, and it will always return an array.
You don't need to use split, you can use string operations to get part of the string:
var current = this.id.substr(this.id.indexOf('_') + 1);

reversing a string, why the quotations?

I saw another stackoverflow thread here
one of the answers given was
function reverse(s){
return s.split("").reverse().join("");
}
so my question is, why are there quotation marks for split and join but not reverse?
That's because the 3 functions are different:
String.split( delimiter ); // delimiter = split by what
Array.reverse(); // reverse an array
// unlike other array functions such as sort() or join()
// there is no other option to specify because the function
// does only one thing only one way
Array.join( join_string ); // join_string = what string to insert
// between elements
Whenever you have doubts about how functions work read the documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
Not all functions require one argument. Some take none. Some take two or three. Some have optional arguments.
reverse() is called on an array. The result of split("") being an array of letters (strings of one letter each to be precise).
.split("") Will spit a string based on a given parameter. in this case "" means no delimiter so it will split on each char and return an array of char. then reverse() method is call on that array. once it reversed then we have to join it back to the string. join("") will do that task for you. in this case "" means no delimiter for join so array will join each char together.

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

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

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

javascript spilt to get part of the word

I tried use javascript spilt to get part of the word : new from What#a_new%20day
I tried code like this:
<script>
var word="What#a_new%20day";
var newword = word.split("%20", 1).split("_", 2);
alert(newword);
</script>
But caused:
Uncaught TypeError: Object What#a_new has no method 'split'
Maybe there have more wiser way to get the word which I need. So can anyone help me? Thanks.
split returns an array, so the second split is trying to operate on the array returned by the first, rather than a string, which causes a TypeError. You'll also want to add the correct index after the second call to split, or newword will also be an array, not the String you're expecting. Change it to:
var newword = word.split("%20", 1)[0].split("_", 2)[1];
This splits word, then splits the string at index 0 of the resulting array, and assigns the value of the string at index 1 of the new array to newword.
Regex to the rescue
var word="What#a_new%20day";
var newword = word.match(/_(.+)%/)[1];
alert(newword);
this returns the first ([1]) captured group ((...)) in the regex (_(.+)%) which is _ followed by any character (.) one or more times (+) followed by %.
the result of a split is an array, not a string. so what you need to do is
<script>
var word="What#a_new%20day";
var newword = word.split("%20", 1)[0].split("_", 2);
alert(newword);
</script>
notice the [0]
split returns an array:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
word.split("%20", 1);
gives an array so you cannot do :
(result from above).split("_", 2);
If split is what your after, go for it, but performance wise, it would be better to do something like this:
var word="What#a_new%20day";
var newword = word.substr(word.indexOf('new'),3)
alert(newword);
Live example: http://jsfiddle.net/qJ8wM/
Split searches for all instances of %20 in the text, whereas indexOf finds the first instance, and substr is fairly cheap performance wise as well.
JsPerf stats on split vs substring (a general case): http://jsperf.com/split-vs-substring

Categories

Resources