如何仅从URL javascript或jquery中提取数值
有一个包含数值的URL。需要提取该数值。但是URL中的数值位置不是常量。需要一种通用的方法来提取。无法使用拆分方法,因为值的位置不是常量 例如:如何仅从URL javascript或jquery中提取数值,javascript,jquery,Javascript,Jquery,有一个包含数值的URL。需要提取该数值。但是URL中的数值位置不是常量。需要一种通用的方法来提取。无法使用拆分方法,因为值的位置不是常量 例如: 1. https:// www.example.com/A/1234567/B/D?index.html 2. http://www.example.com/A?index.html/pd=1234567 3. http://www.example.com/A/B/C/1234567?index.html 因此,上述三个URL有一个位置不是常数的数值
1. https:// www.example.com/A/1234567/B/D?index.html
2. http://www.example.com/A?index.html/pd=1234567
3. http://www.example.com/A/B/C/1234567?index.html
因此,上述三个URL有一个位置不是常数的数值。
您能否提供一个通用方法,在该方法中我可以获得预期的输出,如“1234567”。使用基本正则表达式:
"http://www.example.com/A?index.html/pd=1234567".match( /\d+/ );
这将返回字符串中的第一个数字序列。在上述情况下,我们得到以下结果:
[ "1234567" ]
这是一个例子
请注意,这意味着url中没有其他数字序列否哪里 另一个正在工作的:)
var str=“https://www.example.com/A/1234567/B/D?index.html”;
var numArray=[];
对于(变量i=0,len=str.length;i
查看添加到@Jonathan的,如果您想匹配所有的数值,那么您可以使用
htmlContent.match(/\d+/g)
从URL中删除一个数字就像从任何字符串中删除一个数字,只要您的链接遵循每次都具有相同格式的一般规则:只意味着一个数字。可能您会遇到端口问题
也就是说,您需要提取URL:window.location.pathname
,这样您将只获得URL中“”后面的内容。
然后用正则表达式解析URL字符串:urlString.match('[\\d]+')代码>
例如:
function getUrlId(){
var path = window.location.pathname;
var result = path.match('[\\d]+');
return result[0];
};
var str ="https:// www.example.com/A/1234567/B/D?index.html";
var numArray = [];
for (var i = 0, len = str.length; i < len; i++) {
var character = str[i];
if(isNumeric(character)){
numArray.push(character);
}
}
console.log(numArray);
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
function getUrlId(){
var path = window.location.pathname;
var result = path.match('[\\d]+');
return result[0];
};