Date: February 18th, 2010
Cate: Uncategorized
Tags:

Javascript 字串的擴充 functions

一些 Javascript 的 String 擴充功能:

Substr
myVar = substr2(myVar, x, y); //Your function
myVar = myVar.substr(x, y); //built-in function

Trim
String.prototype.trim = function(){return
(this.replace(/^[\s\xA0]+/, “”).replace(/[\s\xA0]+$/, “”))}

startsWith
String.prototype.startsWith = function(str)
{return (this.match(“^”+str)==str)}

 endsWith
String.prototype.endsWith = function(str)
{return (this.match(str+”$”)==str)} 

Examples:
var myStr = “  Earth is a beautiful planet  ”;
var myStr2 = myStr.trim();  
//==“Earth is a beautiful planet”;

if (myStr2.startsWith(“Earth”)) // returns TRUE

if (myStr2.endsWith(“planet”)) // returns TRUE

if (myStr.startsWith(“Earth”))
// returns FALSE due to the leading spaces…

if (myStr.endsWith(“planet”))
// returns FALSE due to trailing spaces…

參考連結: http://www.tek-tips.com/faqs.cfm?fid=6620

Leave a Reply

 Name

 Mail

 Home

[Name and Mail is required. Mail won't be published.]