0

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?

Karlom
  • 13,323
  • 27
  • 72
  • 116
  • I want to remove the left part, ie `$foo$bar$` – Karlom Mar 19 '17 at 09:30
  • 1
    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. – Karlom Mar 19 '17 at 09:33
  • Possible duplicate of [Cutting a string at nth occurrence of a character](http://stackoverflow.com/questions/5494691/cutting-a-string-at-nth-occurrence-of-a-character) – Martin Schneider Mar 19 '17 at 09:38

2 Answers2

2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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
Sachin Kumar
  • 3,001
  • 1
  • 22
  • 47