我想使用 javascript 从字符串中提取子字符串,然后将其作为字符集替换为另一个字符。
我知道字符串的前缀和后缀。前缀和后缀之间是我想要提取并替换其上的字符集的变量子字符串。
例如,该字符串代表错误 URL。我需要从中提取 URL,在本例中为:https%3A//revoked.badssl.com/
然后替换%3A
与 :
逻辑是,前缀是:about:neterror?e=nssFailure2&u=
后缀是 &c=UTF*
因为我不关心 &
之后的字符串的其余部分性格。
我可能需要使用正则表达式。但是,我知道如何使用正则表达式来比较字符串是否与特定模式匹配。但我想知道如何使用正则表达式提取子字符串?
about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&
f=regular d=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.
%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code
%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE
%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A
编辑: 当我尝试这个脚本时:
var myString="about:neterror?e=nssFailure2&u=https%3A//abcde.somethig/&c=UTF-8&f=regular&d=An%20error%20occurred%20during%20a%20connection%20to%20abcde.somethig.\
%0A%0ACannot%20communicate%20securely%20with%20peer%3A%20no%20common%20encryption%20algorithm%28s%29.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20\
title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A";
console.log(myString.replace(/^about:neterror\?e=nssFailure2&u=(https)%3A(.*)&c=UTF8.*$/, "$1:$2"));
注意:我使用了 \
在行尾只是为了在编辑器中中断字符串。但它不是原始字符串的一部分。
我得到的输出与输入相同。
注2:
如果我只想使用 & 作为后缀的 strat 标记怎么办?我用过console.log(myString.replace(/^about:neterror\?e=nssFailure2&u=(https)%3A(.*)&.*$/, "$1:$2"));
但它打印:https://abcde.somethig/&c=UTF-8&f=regular
我想要:https://abcde.somethig/
最佳答案
我能想到的最简单的方法是不使用一些复杂的正则表达式并假设 &c 和 &u 是静态的,这是 - 首先按照 Jedi 的建议解码字符串
var str = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regulard=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A"
var url = decodeURIComponent(str).split("&u=")[1].split("&c")[0];
console.log(url)
这就是我关闭重复项的原因:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var str = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regulard=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A"
var url = getParameterByName("u",str);
console.log(url);
关于javascript - 如何从字符串中提取可变子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44872776/