GPack GPack - 5 months ago 12
JSON Question

JSON object and string function

I am trying to call startsWith() string function on a JSON property value:

{"message":"xyzabc"}

var jsonResponse = JSON.parse(httpResponse.text);
var stringMessage = jsonResponse.message.toString();
if(stringMessage.startsWith('xyz')) {
...
}


but I get the error:


Object xyzabc has no method 'startsWith'


How can I do that?

The code is running on server side, Express on Node.js

Answer

It may be happen that your browser does not support the startsWith() function so you can use use the RegExp to overcame this problem like this...

var jsonObject={message:"xyzHELLO"};
var regex=new RegExp("^xyz");
if(regex.test(jsonObject["message"])){
alert("hello");
}

Live Demo HERE

[EDIT]

If you want to add the function startsWith() in your each and every string than you can add like this

if (String.prototype.startsWith !== "function") {
    String.prototype.startsWith = function (searching) {
        var regex = new RegExp("^" + searching);
        if (regex.test(this.toString())) {
            return true;
        }
        else {
            return false;
        }
    }
}

and after that you can use like this:

var jsonObject = { message: "xyzHELLO" };
if (jsonObject["message"].toString().startsWith("xyz")) {
    alert("start with");
}
else {
    alert("not start with");
}