Convert Object to String
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?
Javascript has no startsWith method. You can use
msgstring.indexOf('string') === 0
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!
}
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.
There is no startsWith()
function in JavaScript. You need to write one yourself.
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"
Try this:
var msgstring = msg.value;
if(!msgstring.indexOf("string")){
//Doing stuff!
}
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.
精彩评论