I need to split a string, but grab the second half of the string...
var str = "How, are, you, doing, today?";
var res = str.split(",", 3);
console.log(res);
I need to split a string, but grab the second half of the string...
var str = "How, are, you, doing, today?";
var res = str.split(",", 3);
console.log(res);
Returns "How,are,you."
How can I get "doing,today?"
?
Perhaps split()
isn't the best way? All I would like is to do is essentially split the string in half and get both values as different variables.
2 Answers
Reset to default 4You can use split
to get all values (by not passing a number to it), and then use slice
to get values from index 3
to the end of the list of values:
var str = "How, are, you, doing, today?";
var res = str.split(",").slice(3);
console.log(res);
If you don't know what the length of your CSV string will be, you could:
const get2ndHalf = (csv, del = ',') => {
const arr = csv.split(del);
return arr.slice(Math.ceil(arr.length / 2)).join(del).trim();
}
console.log( get2ndHalf("How, are, you, doing, today?") )
console.log( get2ndHalf("This; one; is; a; tiny; bit; longer!", ";") ) // using delimiter ;
console.log( get2ndHalf("One") ) // Hummmm maybe rather Math.floor instead of math.ceil!
Or even better, to prevent empty results (like in the example above) use Math.floor
const get2ndHalf = (csv, del = ',') => {
const arr = csv.split(del);
return arr.slice(Math.floor(arr.length / 2)).join(del).trim();
}
console.log( get2ndHalf("How, are, you, doing, today?") )
console.log( get2ndHalf("This; one; is; a; tiny; bit; longer!", ";") ) // using delimiter ;
console.log( get2ndHalf("One") ) // Now this one is legit!
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745307020a4621772.html
评论列表(0条)