简体   繁体   中英

Regex to get string with complex structure in Javascript

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.

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+$)/) ); 

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.

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM