需要帮助获取URL的特定部分并动态替换它
例如:
https://m.facebook.com/logout.php?h=的 BfcGpI0GW8PKKFtX & T公司= 1494184226&安培; BUTTON_NAME =注销&安培; button_location =设置
对于此示例,我需要替换 BfcGpI0GW8PKKFtX 并在该点之前和之后加载URL。有没有办法做到这一点?具体来说,它最终看起来像这样:
https://m.facebook.com/logout.php?h=的 + replacemen + & T公司= 1494184226&安培; BUTTON_NAME =注销&安培; button_location =设置。任何帮助将不胜感激。
答案 0 :(得分:0)
您还可以使用正则表达式:
var regex = /.+(\?h=|&h=)([^&]+).+/g;
var url = 'https://m.facebook.com/logout.php?h=BfcGpI0GW8PKKFtX&t=1494184226&button_name=logout&button_location=settings';
var m, newUrl;
while ((m = regex.exec(url)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
++regex.lastIndex;
}
newUrl = url.replace(m[2], 'REPLACEMENT');
// m[2] because the first match is the whole url and
// the second one is "?h=" (or "&h=").
// the third one (index 2) is the one you want to replace.
document.getElementById("output").innerHTML = newUrl;
}
<span id="output"></span>
唯一的问题是,“h”参数必须是第一个,在“?”之后。
编辑:我调整了正则表达式,以便“h”参数可以在网址中的任何位置。