Convert an object to a string

I have an object returned from a field msgthat is an object. I tried to get the value from msg and convert it to a string to use .startswith(). I am trying to do 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?

+3
source share
7 answers

Javascript does not have a beginWith method. you can use

msgstring.indexOf('string') === 0
+16
source

The error is correct; JS does not have a built-in startsWithobject method string.

You can create it yourself by the prototype producer or use the 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!
 }
+2
source

, , , "startsWith". JavaScript .

, :

, "StartsWith" ?

, Javascript .

0

JavaScript startsWith(). .

0

, , ( msgstring) , startsWith. .

, - :

msgstring.substr(0, 6) == "string"
0

:

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

, JS launchWith, .

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

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

0
source

All Articles