简体   繁体   中英

Using replace to select part of a URL

Hello I'm new to javascript and I need a little help with regex/replace

I want to take a url for example (url case 1)

http://url.com/_t_lastUpdate_2670619?location=50457347

or (url case 2)

http://url.com/_t_2670619

I want to select in this case just

_t_2680619

Ignore everything after "?" and before (underscore)t(underscore)

Is it possible with regex/replace? the only thing I managed to do was select numbers only with

var _t__and_number = document.URL.replace(/[^\d]/g, '');
alert(_t__and_number);

But that doesn't solve my problem if there's something like url case 1

(if I could get just the first number even without the (underscore)t(underscore) it would already help me a lot. Thanks

Solutions:

onetrickpony /michaelb958:

var _t__and_number = window.location.pathname;
alert(_t__and_number);

ermagana:

var _t__and_number = document.URL.replace(/\?.*/g, '').match(/.*\/(.*)/)[1];
alert(_t__and_number);

First Part like case (1) and (2)

    var s = '//url.com/_t_522121?location=50457347';
    var n = s.lastIndexOf('/');
    var result = s.substring(n + 1);
    alert(result);

    n = result.indexOf('?');
    result = result.substring(0, n);
    alert(result);

onetrickpony所建议,如果这是您当前正在浏览的URL,则window.location.pathname将产生该URL的一部分。

If you're trying to pull out the value after the last / and before the ? you could try something like this

url.replace(/\?.*/g, '').match(/.*\/.*(_t_.*)/)[1]

The replace removes everything from the ? and forward, the match creates a group of the values found after the last forward slash which is then accessed by the index 1

Hope this helps.

here is the jsfiddle to show it works: My JsFiddle

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