Karlom
Karlom

Reputation: 14834

How to cut string based on 3rd occurrence of a character?

Assuming that I have a string like $foo$bar$baz $5

I have tried to split the string to an array by `$', then remove the first and second elements, and then convert the array to a new string. but I'm wondering if there is a more elegant way to do so?

Upvotes: 0

Views: 569

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386600

You could remove the first two occurences of $ and some text with an empty string.

^(\$[^$]+){2}\$    regular expression
^                  start of the string
  \$               search for $ literally
    [^$]           search for any character but not $
        +          quantifier one or more
 (       )         group
          {2}      quantifier for exactly two times
 (       ){2}      get the group only two times
             \$    get the third $

var string = '$foo$bar$baz $5',
    result = string.replace(/^(\$[^$]+){2}\$/, '');

console.log(result);

Upvotes: 2

Sachin Kumar
Sachin Kumar

Reputation: 3240

Review it:-

var str = '$foo$bar$baz $5',
delimiter = '$',
start = 3,
tokens = str.split(delimiter).slice(start),
result = tokens.join(delimiter);
console.log(result); //baz $5

Upvotes: 0

Related Questions