user6875880 user6875880 - 1 year ago 47
Javascript Question

How to extract a variable sub-string from a string

I want o 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 prefix and postfix is the variable sub-string that I want to extract and replace set of characters on it.

For example, this string represents error URL. I need to extract the URL from it which in this example is:

then replace

The logic is that, the prefix is:
and the postfix is
as I do not care about the rest of the string after &.

I probably need to use Regex. However, I know how to use Regex to compare whether a string matches a specific pattern or not. But I wonder how to use Regex to extract a sub-string?


When I try this script:

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.\
console.log(myString.replace(/^about:neterror\?e=nssFailure2&u=(https)%3A(.*)&c=UTF8.*$/, "$1:$2"));

NOTE: I used
at the end of the line just to break the string in the editor. But it is not part of the original string.
I get output identical to the input.

What about if I want to just use & as mark of strat for the postfix? I used
console.log(myString.replace(/^about:neterror\?e=nssFailure2&u=(https)%3A(.*)&.*$/, "$1:$2"));
but it prints:
and I want:

Answer Source

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//"

var url = decodeURIComponent(str).split("&u=")[1].split("&c")[0];

And here is why I close as duplicate:

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//"

var url = getParameterByName("u",str);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download