Reputation: 44842
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?
Upvotes: 3
Views: 6020
Reputation: 890
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.
Upvotes: 0
Reputation: 17427
Try this:
var msgstring = msg.value;
if(!msgstring.indexOf("string")){
//Doing stuff!
}
Upvotes: 0
Reputation: 2426
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"
Upvotes: 0
Reputation: 318508
There is no startsWith()
function in JavaScript. You need to write one yourself.
Upvotes: 0
Reputation: 7855
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.
Upvotes: 0
Reputation: 66389
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!
}
Upvotes: 2
Reputation: 75599
Javascript has no startsWith method. You can use
msgstring.indexOf('string') === 0
Upvotes: 16