Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

startsWith in Node.js: TypeError: undefined is not a function

Tags:

node.js

I got an error using startsWith in Node.js

Script sw.js

//startswith
var str = 'Sein oder nicht sein, dass ist hier die Frage'; console.log(str.startsWith('Sein oder'));
// true
console.log(str.startsWith('nicht sein'));
// false
console.log(str.startsWith('nicht sein', 10));
// true

Output of the script:

/Users/.../sw.js:2
 = 'Sein oder nicht sein, dass ist hier die Frage'; console.log(str.startsWith
                                                                    ^
TypeError: undefined is not a function
    at Object.<anonymous> (/Users/.../sw.js:2:76)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Node version (not sure if that is relevant)

node -v
v0.12.8
like image 641
jpsstack Avatar asked Apr 19 '26 18:04

jpsstack


1 Answers

Your node version doesn't support ecmascript6 features, such as String.prototype.startsWith(). Node's latest version is 6.9.2 / 7.3.0 at the time of writing this, so you should consider upgrading node to the latest version as yours is pretty old.

However, if that's not possible for you, you can use the polyfill found on mdn:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}
like image 87
baao Avatar answered Apr 21 '26 07:04

baao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!