JavaScript 內建物件的 prototype 屬性允許我們為所有字串實例一次性新增方法。本文彙整實務常用的字串擴充方法,並說明 prototype 運作機制與注意事項。
// 1. 計算中英文混合長度(中文算 2 字元)
String.prototype.ChineseLength = function() {
return this.replace(/[^\x00-\xff]/g, "**").length;
};
// 2. 判斷是否以指定字串結尾
String.prototype.EndsWith = function(str) {
return this.substr(this.length - str.length) === str;
};
// 3. 去除左側空白
String.prototype.LeftTrim = function() {
return this.replace(/^\s*/, "");
};
// 4. 去除右側空白
String.prototype.RightTrim = function() {
return this.replace(/\s*$/, "");
};
// 5. 判斷是否以指定字串開頭
String.prototype.StartsWith = function(str) {
return this.substr(0, str.length) === str;
};
// 6. 去除雙側空白(ES5 已內建 trim,此為相容寫法)
String.prototype.Trim = function() {
return this.replace(/^\s*|\s*$/g, "");
};
var msg = " Hello 中文 ";
console.log(msg.ChineseLength()); // 13
console.log(msg.Trim()); // "Hello 中文"
console.log(msg.StartsWith("He")); // true
console.log(msg.EndsWith("文")); // true
// 新增自定方法
String.prototype.myMethod = function() {
return "my define method";
};
// 覆寫 toString
String.prototype.toString = function() {
return "my define toString method";
};
var s = new String("foo");
console.log(s.myMethod()); // "my define method"
console.log(s.toString()); // "my define toString method"
console.log("foo".toString()); // "my define toString method" (字面值也受影響)
String.prototype 整個重新指派為新物件(如 String.prototype = new Employee()),否則原有方法全失,且實例無法存取新原型屬性。function Person() { this.name = "Rob"; }
function Employee() { this.dept = "HR"; }
Employee.prototype = new Person();
var ken = new Employee();
console.log(Person.prototype.isPrototypeOf(ken)); // true
console.log(Object.prototype.isPrototypeOf(ken)); // true
startsWith、endsWith、trim、padStart 等),僅在舊環境補上 Polyfill。Object.defineProperty 設定 enumerable: false,避免 for...in 遍歷汙染。string.extensions.js,載入順序置於業務邏輯之前。善用 String.prototype 能大幅提升字串處理的可讀性與復用性,但需謹慎避免汙染全域原型、覆寫內建行為,並在現代環境優先採用標準 API。