最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Split string, get second half - Stack Overflow

programmeradmin1浏览0评论

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.

Share Improve this question edited Aug 30, 2019 at 23:59 Djaouad 22.8k4 gold badges36 silver badges56 bronze badges asked Aug 30, 2019 at 23:53 SAASAA 371 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

You 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!

发布评论

评论列表(0)

  1. 暂无评论