Rocker rock
Rocker rock

Reputation: 155

Split a string to hold first few values only

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

Answers (1)

Tushar
Tushar

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.

  1. \d+: Match one or more digits
  2. \|: Match pipe | literal
  3. {4}: Match preceding group exactly four times

match returns an array, to get the complete match use [0].

Upvotes: 7

Related Questions