2

I have a link look like:

var str = "http://example.com/ep-1-29838.html";

I want to get only 29838

I tried with:

str = str.replace(^([-])\/([.html])$\w+, "");

I don't have many experiences with Regex. Thanks.

4
  • 2
    Does the filename always follow this structure? Commented Jun 11, 2018 at 8:36
  • @31piy of course. this filename always have the same structure Commented Jun 11, 2018 at 8:38
  • 1
    When the number always comes right before .html you can try this regex ([0-9]+)\.html Commented Jun 11, 2018 at 8:39
  • @wayneOS good suggest! Commented Jun 11, 2018 at 8:42

3 Answers 3

5

Match the last digits followed by a dot and file extension:

var str = "http://example.com/ep-1-29838.html";
console.log(
  str.match(/\d+(?=\.\w+$)/)
);

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution very smart!
1

This could be an approach:

"http://example.com/ep-1-29838.html".match(/(\d+)\.html$/)

It basically means "match and store in a group one or more digit (0-9) that are followed by .html at the end of the string".

The value returned is an array of two element, you're interested in the second one.

1 Comment

Cool solution but get more step to get.
1

You don't have to use regex if it's this rigid - more readable to me like this:

var str = "http://example.com/ep-1-29838.html";

str = str.split('-') /* split the string on hyphen */
        .pop() /* get last of generated array */
        .replace('.html', ''); /* now remove the file extension */

console.log(str);

3 Comments

Isn't it generally the other way around? It's nice to use regex if you can, but if you can't, then you have to resort to language-specific string manipulation
I like method match to resolve my problem. It special. Your solution is general in any case. Thanks.
@CertainPerformance I guess all devs work in different ways - if there isn't s substantial performance loss (I haven't checked in this case but I doubt it), then readability wins every time for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.