Skip to content Skip to sidebar Skip to footer

How To Extract A Variable Sub-string From A String

I want to extract a sub-string from a string using javascript, then replace as set of characters by another character. I know the prefix and postfix of the string. Between the pre

Solution 1:

Simplest I can think of without using some complex regex and assuming the &c and &u are static, is this - first decoding the string as suggested by 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)

And here is why I close as duplicate:

functiongetParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = newRegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) returnnull;
    if (!results[2]) return'';
    returndecodeURIComponent(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);

Solution 2:

You can capture the sub string you need and then use back reference to extract and reformat it:

var s = "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 url = s.replace(/^about:neterror\?e=nssFailure2&u=(https)%3A(.*)&c=UTF[\s\S]*$/, "$1:$2")

console.log(url)

Using decodeURIComponent:

var s = "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 url = decodeURIComponent(s).replace(/^about:neterror\?e=nssFailure2&u=(.*)&c=UTF[\s\S]*$/, "$1")

console.log(url)

Post a Comment for "How To Extract A Variable Sub-string From A String"