Reputation: 155
I have a string,
var str = '12990|2346|5771|22523|73|16660|16770|16205|8407|13691|'
I want to split this string to hold first five values like 12990|2346|5771|22523|73
I have tried with below logic
str.split('|').slice(0,5)
But it returns in an array format. I do not want it like that.
Upvotes: 2
Views: 77
Reputation: 87233
You can join the sliced array using join()
str.split('|').slice(0, 5).join('|');
var str = '12990|2346|5771|22523|73|16660|16770|16205|8407|13691|';
console.log(str.split('|').slice(0, 5).join('|'));
OR, regex can also be used with match()
str.match(/\d+(\|\d+){4}/)[0]
var str = '12990|2346|5771|22523|73|16660|16770|16205|8407|13691|';
console.log(str.match(/\d+(\|\d+){4}/)[0]);
The regex will match one or more digits followed by four instances of pipe followed by digits.
\d+
: Match one or more digits\|
: Match pipe |
literal{4}
: Match preceding group exactly four timesmatch
returns an array, to get the complete match use [0]
.
Upvotes: 7