0

Suppose I have a string like this

var str = 'E2*2001/116*0364*31'

What I want is to find the 3rd occurrence of * in the string and print up to that from starting.

So result would be E2*2001/116*0364*

I have tried something like this jsfiddle.

Corresponding code

var str = 'E2*2001/116*0364*31',
delimiter = '*',
start = 0,
var pos=getPosition(str, *, 3);
alert(pos);
tokens = str.substring(start, getPosition(str,*,3)),
result = tokens;


document.body.innerHTML = result;


function getPosition(str, m, i) {
   return str.split(m, i).join(m).length;
}

But unable to get the output.

Can anyone please assist.

Navoneel Talukdar
  • 3,964
  • 4
  • 19
  • 39
  • 1
    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) – Hanky Panky Apr 05 '16 at 08:00

3 Answers3

2

Try this.

str.split('*').slice(0,3).join('*') + '*';
Lewis
  • 13,134
  • 12
  • 62
  • 81
1
var str = 'E2*2001/116*0364*31';
console.log(str.match(/^([^*]*\*){3}/)[0]);              // E2*2001/116*0364*
console.log(str.match(/^([^*]*\*){3}/)[0].slice(0, -1)); // E2*2001/116*0364
Qwertiy
  • 17,208
  • 13
  • 50
  • 117
0

A solution with String#replace:

var string = 'E2*2001/116*0364*31'.replace(/([^*]+\*){3}/, '');
document.write('<pre>' + JSON.stringify(string, 0, 4) + '</pre>');
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358