Get Off My Lawn
Get Off My Lawn

Reputation: 36311

String prototype works in browser but not in node

Node: 8.1.0

I have the following prototype:

String.prototype.toSlug = function () {
  return (<string>this)
    .trim()
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/[^\w\-]+/g, '')
    .replace(/\-\-+/g, '-')
    .replace(/^-+/, '')
    .replace(/-+$/, '')
}

When I use it, like this:

// Mongoose Database Model:
let project = new ProjectModel
project.slug = title.toSlug()

It doesn't seem to work correctly. All it did was remove the first space and add a dash as seen here:

// Original: "Bed Time Stories"
// Outputs: "BedTime-Stories"
// Expected: "bed-time-stories"

As you can see it didn't even convert the strings to lowercase.

However when I test this at jsfiddle, it creates the correct output string. What is causing this?

Upvotes: 1

Views: 77

Answers (1)

marvel308
marvel308

Reputation: 10458

interface String {
    toSlug(): string;
}

String.prototype.toSlug = function () {
  return (<string>this)
    .trim()
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/[^\w\-]+/g, '')
    .replace(/\-\-+/g, '-')
    .replace(/^-+/, '')
    .replace(/-+$/, '')
}

var str = "Bed Time Stories";

console.log(str.toSlug());

I found the error, The interface provides the contract for TypeScript, allowing visibility of the new method. The JavaScript implementation provides the code that will be executed when the method is called. That was missing from the code

Sources : Extending functionality in TypeScript

Upvotes: 1

Related Questions