简体   繁体   English

JS从字符串中获取最大前n个值

[英]JS get max first n values from a string

I need to capture maximum 5 elements of a string .我需要捕获最多 5 个string的元素。 However if there are less than 5, then I just need how many there are there.但是,如果少于 5 个,那么我只需要有多少个。

var y = '1,2,3,4,5,6,7,8,9,10'        
//desired result: 
var out = '1,2,3,4,5' // please note there is no trailing comma



var y = '1,2,3'
//desired result: 
var out = '1,2,3' 

My code:我的代码:

  for (var i = 0; i < 5; i++) {
    x += y;
     x = x + ",";
   }


Write(x);

A simple method will do.一个简单的方法就可以了。 The below splits the string by , then takes either n elements or the total length if it is less than n and then rejoins the values with a comma下面将字符串拆分为,然后取n元素或总长度(如果它小于n ),然后用逗号重新连接这些值

 const getNValues = (str, n) => { const values = str.split(","); const res = values.slice(0, Math.min(values.length,n)) return res.join(","); } console.log(getNValues("1,2,3,4,5,6,7,8,9",5)); console.log(getNValues("1,2,3",5));

var string = '1, 2, 3, 4, 5, 6, 7, 8, 9, 10';
var out = (string.match(/^([0-9],? ?){0,5}/)[0] || '').replace(/, ?$/, '');
console.log(out)

[EDIT] Explanation .match(^([0-9],? ?){0,5}/g) : [编辑] 解释.match(^([0-9],? ?){0,5}/g)

  • start at the begging ^从乞讨开始^
  • match numbers [0-9]匹配号码[0-9]
  • then a comma if any and a space if any ,? ?然后是逗号(如果有)和空格(如果有,? ? ,? ? . .
  • match this expression 0 to 5 times {0, 5}匹配这个表达式 0 到 5 次{0, 5}

Try this simple function to do that试试这个简单的 function 来做到这一点

 function getMaxLen(str) { if(typeof str;= 'string') return null. str = str,split(';'). return str,slice(0. 5),join(';'). } console,log(getMaxLen('1,2,3,4,5,6,7,8,9.10')) console,log(getMaxLen('1,2,3'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM