nikitha
nikitha

Reputation: 179

Split the string based on regex pattern

I am new to using regular expression. Given the string, I am trying to achieve the following:

actStr1 = 'st1/str2/str3'
expStr1 = 'str3'

actStr2 = 'str1/str2/str3 // str4'
expStr2 = 'str3 // str4'

actStr3 = 'a1/b1/c1 : c2'
expStr3 = 'c1 : c2'

In both cases, i would like to find the last string delimited by '/'

i.e, '/' like %s\/%s. delimiter '/' having strings on both sides

result1 = 'str3 // str4'
result2 = 'str3'

I tried different patterns using regex, but it incorrectly returns 'str4' delimited by '//'.

How do I avoid this?

Thanks

Upvotes: 0

Views: 116

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

Instead of using String.prototype.split(), try to use String.prototype.match() to directly target what you need:

var testStrings = [ 'str1/str2/str3',
                    'str1/str2/str3 // str4',
                    'a1/b1/c1 : c2' ];

var re = new RegExp('[^/]*(?://+[^/]*)*$');

testStrings.forEach(function(elt) {
    console.log(elt.match(re)[0]);
});
/* str3
   str3 // str4
   c1 : c2 */

Less straight forward, you can also use a replacement strategy with String.prototype.replace(). The idea is to remove all until the last slash not preceded and not followed by an other slash:

var re = new RegExp('(?:.*[^/]|^)/(?!/)');

testStrings.forEach(function(elt) {
    console.log(elt.replace(re, ''));
});

Upvotes: 1

Hichem ben chaabene
Hichem ben chaabene

Reputation: 145

I think you can resolve this considering using arrays too!

function lastSlug(str) {
  // remove the '//' from the string
  var b = str.replace('//', '');
  // find the last index of '/'
  var c = b.lastIndexOf('/')  + 1;
  // return anything after that '/' 
  var d = str.slice(c);
  return d;
}

Demo

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 30995

You could use a regex like this:

\/(\w+(?:$| .*))

Working demo

And grab the content from capturing group

Upvotes: 0

Related Questions