[英]Using replace to select part of a URL
Hello I'm new to javascript and I need a little help with regex/replace 您好,我是javascript新手,我需要一些有关正则表达式/替换的帮助
I want to take a url for example (url case 1) 我想以一个网址为例(网址情况1)
http://url.com/_t_lastUpdate_2670619?location=50457347
http://url.com/_t_lastUpdate_2670619?location=50457347
or (url case 2) 或(网址大小写2)
I want to select in this case just 我想在这种情况下选择
_t_2680619
Ignore everything after "?" 忽略“?”之后的所有内容 and before (underscore)t(underscore)
和之前(下划线)t(下划线)
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 但这并不能解决我的问题,如果出现类似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 (如果即使没有(underscore)t(underscore),我也只能得到第一个数字,那已经对我有很大帮助。谢谢
onetrickpony /michaelb958: onetrickpony / michaelb958:
var _t__and_number = window.location.pathname;
alert(_t__and_number);
ermagana: ermagana:
var _t__and_number = document.URL.replace(/\?.*/g, '').match(/.*\/(.*)/)[1];
alert(_t__and_number);
First Part like case (1) and (2) 第一部分,如情况(1)和(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
向前和向前,匹配会创建一组在最后一个正斜杠之后找到的值,然后由索引1访问
Hope this helps. 希望这可以帮助。
here is the jsfiddle to show it works: My JsFiddle 这是展示效果的jsfiddle : 我的JsFiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.