Reputation: 987
I need to capture maximum 5 elements of a string
. However if there are less than 5, then I just need how many there are there.
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);
Upvotes: 0
Views: 57
Reputation: 1546
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)
:
^
[0-9]
,? ?
.{0, 5}
Upvotes: 1
Reputation: 390
Try this simple function to do that
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'))
Upvotes: 1
Reputation: 136154
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
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));
Upvotes: 2