0

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

9
  • 1
    can you please post the sample JSON response text? Commented Jun 24, 2016 at 7:22
  • What is .message in your jsonResponse? It's hard to think out why something does not work, when you don't even know how does it look like! Commented Jun 24, 2016 at 7:22
  • Post your JSON Format. Commented Jun 24, 2016 at 7:23
  • In what browser are you testing this? Commented Jun 24, 2016 at 7:28
  • Are you using a browser that supports .startsWith()? Also, you're not operating on a JSON property value, you've called .toString() on an object property value, and are using .startsWith() on the result. There's no such thing as a JSON object. Commented Jun 24, 2016 at 7:29

3 Answers 3

1

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");
}

[EDIT]

if (String.prototype.startsWith !== "function") {
    String.prototype.startsWith = function (searching) {
        if (this.toString().indexOf(searching) == 0) {
            return true;
        }
        else {
            return false;
        }
    }
}

As per the comment by @nnnnnn and I also think it is good practice if we use the native function of the JavaScript, Thanks @nnnnnn.

Sign up to request clarification or add additional context in comments.

5 Comments

The code is running on server side, Express on Node.js
When you post the question at that time you does not describe it.
your solution works fine, thanks. I will try the other solution with own coded function startsWith() too.
Welcome. If you wan to use this code like yourString.startsWith() function than you can also add that function in the in the String class
If you're writing a generic startsWith() it would be safer to code the function with .indexOf(), because then you don't have to worry about the test string needing to be escaped for use in building a regex.
1

Please double check your input JSON. Your code works like a charm with a correct JSON input in httpResponse.text.

var json = '{"message": "xyztest"}';
var jsonResponse = JSON.parse(json);
var stringMessage = jsonResponse.message.toString();

if(stringMessage.startsWith('xyz')) {
    alert('It works!');
}

Also please make sure the browser you are working in supports startsWith method. Here you can find a list with all supported browsers.

If you need to work around the browser compatibility issues, you can use the widely supported indexOf method.

if(stringMessage.indexOf('xyz') === 0) {
    alert('It works!');
}

HERE is a Fiddle for both cases.

2 Comments

The code is running on server side, Express on Node.js
That's new, wasn't included in your original question. The code should work anyway.
1

Apparently, Js has startsWith function for the strings. However, using your own function to see if the string starts with the value should cause no error.

 function StartsWith(s1, s2) {
      return (s1.length >= s2.length && s1.substr(0, s2.length) == s2);
    }
    var jsonResponse = JSON.parse(httpResponse.text);
   var stringMessage = jsonResponse.message.toString();
   if(StartsWith(stringMessage,'xyz')) {
      //Doing Stuff!
    }

5 Comments

"JS has no native startsWith" - Well...it does. (But it's not supported by IE.)
@nnnnnn i couldn't find it. Read more on using strings javascriptkit.com/javatutors/string4.shtml
@nnnnnn, well, i see. Thanks for the insights.
your solution works well, I mark the other solution with regex as first in time (1 min difference) only. Thanks.
@GPack hehe, well you chose a cannon to kill a fly :) . Thanks for the upvote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.