String method extension in Javascript _ javascript skills

Source: Internet
Author: User
Expanded several common methods. For more information, see The Code is as follows:


String. prototype. EndWith = function (str ){
If (str = null | str = "" | this. length = 0 | str. length> this. length)
Return false;
If (this. substring (this. length-str. length) = str)
Return true;
Else
Return false;
Return true;
}
String. prototype. StartWith = function (str ){
If (str = null | str = "" | this. length = 0 | str. length> this. length)
Return false;
If (this. substr (0, str. length) = str)
Return true;
Else
Return false;
Return true;
}
String. prototype. Trim = function (){
Return this. replace (/(^ \ s *) | (\ s * $)/g ,"");
}
String. prototype. ltrim = function (){
Return this. replace (/(^ \ s *)/g ,"");
}
String. prototype. rtrim = function (){
Return this. replace (/(\ s * $)/g ,"");
}
String. format = function (str ){
Var I = 1, args = arguments;
Var str = args [0];
Var re =/\ {(\ d +) \}/g;
Return str. replace (re, function () {return args [I ++]});
};
Var Json2string = function (obj ){
Var t = typeof (obj );
If (t! = "Object" | obj = null ){
// Simple data type
If (t = "string") obj = "'" + obj + "'";
Return String (obj );
}
Else {
// Recurse array or object
Var n, v, json = [], arr = (obj & obj. constructor = Array );
For (n in obj ){
V = obj [n]; t = typeof (v );
If (t = "string") v = "'" + v + "'";
Else if (t = "object" & v! = Null)
V = Json2string (v );
Json. push (arr? "": "'" + N + "':") + String (v ));
}
Return (arr? "[": "{") + String (json) + (arr? "]": "}");
}
};

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.