2017-08-12 50 views
1

節點: 8.1.0字符串原型作品在瀏覽器,但不是在節點

我有以下的原型:

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

當我使用它,就像這樣:

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

它似乎不能正常工作。所做的只是去掉第一空間,並添加一個破折號在這裏看到:

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

正如你可以看到它甚至沒有轉換字符串爲小寫。

但是,當我測試這個在jsfiddle,它會創建正確的輸出字符串。這是什麼造成的?

+0

是,從字面上如何您鍵入它,用'回報(這個)...'? – adeneo

+0

yes(copy and paste)without –

+0

這是Typescript,你是否在Node中使用它以及小提琴 – adeneo

回答

1
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()); 

我發現了錯誤,該接口提供了TypeScript的契約,允許新方法的可見性。 JavaScript實現提供了在調用方法時將執行的代碼。這是從代碼

來源失蹤:Extending functionality in TypeScript

+0

我正在使用節點'8.1.0'如果這有所作爲 –

+0

你嘗試使用上面的代碼? – marvel308

+0

刪除打字稿元素並不能真正回答問題。 – Andy

相關問題