Thursday, 22 July 2021

Javascript ways to extract values afte r= in string

 1) Regex

/=(.*)/

https://stackoverflow.com/questions/8528873/showing-the-text-after-an-equal-sign-with-regexp


 1) indexOf and substr

function findValue(key, str) {

    var value = '';

    var keyIndex = str.indexOf(key);


    if (keyIndex == -1) {


        return value;


    }


    // Start after equal sign. in string its [key]=value

    var subStrStart = keyIndex + key.length + 1;

    // Is there a comma from subStrStart

    // [key]=value, is there value, ? If not its end of string

    var commaIndex = str.substr(subStrStart).indexOf(',');

    switch (commaIndex) {

        // End of string

        case -1:

            value = str.substr(subStrStart);

            break;


        // In middle of string

        default:

            value = str.substr(subStrStart, commaIndex);

            break;

    }


    return value;

}




No comments:

Post a Comment