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
  • 11,123
  • 26
  • 68
  • 111
  • 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
  • 351,820
  • 24
  • 303
  • 358
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
  • 2,633
  • 1
  • 21
  • 40