3

I've got an object returned from a field msg which is an object. I'm attempted to get the value from msg and convert it into a string so I can use .startswith(). I'm trying the following..

 var msgstring = msg.value
 if(msgstring.startsWith("string")){
    //Doing stuff!
 }

However, I get the following error...

Uncaught TypeError: Object string here has no method 'startsWith'

Where am I going wrong?

Skizit
  • 43,506
  • 91
  • 209
  • 269

7 Answers7

16

Javascript has no startsWith method. You can use

msgstring.indexOf('string') === 0
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
2

The error is correct, JS has no native startsWith method of string object.

You can build it yourself extending the prototype, or use function:

function StartsWith(s1, s2) {
  return (s1.length >= s2.length && s1.substr(0, s2.length) == s2);
}

var msgstring = msg.value;
if(StartsWith(msgstring, "string") {
    //Doing stuff!
 }
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
0

As everybody has already mentioned that there is no startsWith function available with JS and we need to create a one for us. Below is the implementation for the same

if (typeof String.prototype.startsWith != 'function') {
  //Implementation to startsWith starts below
  String.prototype.startsWith = function (str){
    return this.indexOf(str) == 0;
  };
}

after doing this you can call the startsWith function directly with your string. this keyword will be the string on which you have called the function and str will be the string you are comparing with.

Summved Jain
  • 872
  • 2
  • 18
  • 21
0

You are going wrong at assuming that there is a function called "startsWith". There is no such function in JavaScript.

Please have a look at this question:

How to check if a string "StartsWith" another string?

You will find there how you cann add this function to Javascript objects yourself.

Community
  • 1
  • 1
Chris
  • 7,675
  • 8
  • 51
  • 101
0

There is no startsWith() function in JavaScript. You need to write one yourself.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
0

Exactly what you're reading, the string object (your variable msgstring) does not have a method called startsWith. Read more on using strings in here.

You probably want to do something like:

msgstring.substr(0, 6) == "string"
tiagoboldt
  • 2,426
  • 1
  • 24
  • 30
0

Try this:

var msgstring = msg.value;
 if(!msgstring.indexOf("string")){     
         //Doing stuff! 
 }
The Mask
  • 17,007
  • 37
  • 111
  • 185