1

I want to remove everything after /blog/ in the url, here is the input:

http://domain-name.com/blog/a-blog-title

output should be:

http://domain-name.com/blog/

My regexp is \/blog\/.*, but this could remove the /blog/ as well. Obviously I don't want this. Is there a specific way to delete the characters and neglect the matching part? Thanks in advance.

Chang
  • 1,658
  • 1
  • 17
  • 23
  • You you want to remove everything after the specific string `"/blog/"`, or do you want to remove the last segment? –  May 10 '17 at 03:42
  • @torazaburo IMHO, this doesn't seem to be a duplicated question since I want to reserve the `/blog/` part. – Chang May 10 '17 at 03:51
  • The answers in the dup target clearly state that you can retain the `/blog/` portion by replacing with `$1` or `\1`. –  May 10 '17 at 06:16

3 Answers3

5

There are a few ways to do this. Here's one:

var output = "http://domain-name.com/blog/a-blog-title".replace(/\/blog\/.*/, "/blog/")

console.log(output)

That is, match the bit you want to keep and the bit you want to throw away, but replace with the bit you want to keep rather than an empty string.

You can make the replacement string more generic by introducing capturing parentheses in your regex:

var output = "http://domain-name.com/blog/a-blog-title".replace(/(\/blog\/).*/, "$1")

console.log(output)
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
2

If you input strings are consistent in their structure, you can avoid regex and just use substring() and lastIndexOf().

var str='http://domain-name.com/blog/a-blog-title';
console.log(str.substring(0,str.lastIndexOf("/")+1));

If your url strings may vary in their structure (they include a querystring or something) please update your question for clarity.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • The structure url itself is consistent. I could use `split`, `substr` or `lastIndexof`, as you have mentioned. But the point is, I want to use regexp as a cleaner way to solve this problem. Don't want to add any more "noise". Thanks anyway! – Chang May 10 '17 at 03:48
0

Try this helper function:

function cutUrlByIndex(url,n){
    if(n){
       return url.split('/').slice(0,n).join('/');
    }

    return url;
}

Result:

cutUrlByIndex('http://domain-name.com/blog/a-blog-title', 4) //http://domain-name.com/blog
cutUrlByIndex('http://domain-name.com/blog/a-blog-title/ahihi/ahihi', 4) //http://domain-name.com/blog
Dean Ngo
  • 19
  • 4