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
  • 4,393
  • 5
  • 21
  • 42
  • 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
  • 14,132
  • 12
  • 66
  • 87
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
  • 19,681
  • 15
  • 61
  • 128
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
  • 376,160
  • 25
  • 347
  • 392