格式 | camelize | capitalize | underscore | dasherize | inspect |
变形 | toArray | succ | times |
代码如下:
String.specialChar = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'\\': '\\\\'
}
代码如下:
function inspect() {
return this.replace(/[\b\t\n\f\r\\]/,function(a){
return String.specialChar[a];
});
}
代码如下:
function inspect(useDoubleQuotes) {
var escapedString = this.replace(/[\b\t\n\f\r\\]/,function(a){
return String.specialChar[a];
});
if (useDoubleQuotes){
return '"' + escapedString.replace(/"/g, '\\"') + '"';
}
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
}
代码如下:
function inspect(useDoubleQuotes) {
var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) {
if (character in String.specialChar) {
return String.specialChar[character];
}
return character ;
});
if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
}
[html]
附,ASCII控制字符编码表,对应\x00-\x1f:
代码如下:
function toArray() {
return this.split('');
}
代码如下:
function toArray(pattern) {
return this.split(pattern);
}
console.log(toArray.call('my name is xesam',' '));//["my", "name", "is", "xesam"]
代码如下:
function succ() {
return this.slice(0, this.length - 1) + String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
}
代码如下:
function printChar(start,end){
var s = (start + '').charCodeAt()
var e = (end + '').charCodeAt();
if(s > e){
s = [e,e=s][0];
}
for(var i = s ;i <= e; i++){
console.log(String.fromCharCode(i));
}
}
printChar('a','z');
代码如下:
function times(count) {
return count <1 ? '' : new Array(count + 1).join(this);
}
代码如下:
String.prototype.letterTimes = function(count){
var arr = [];
arr.length = count + 1;
return this.replace(/\w/g,function(a){
return arr.join(a);
})
}
console.log('xesam'.letterTimes(3));//xxxeeesssaaammm
代码如下:
function camelize() {
return this.replace(/-+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
}
代码如下:
function capitalize() {
return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
}
代码如下:
function underscore() {
return this.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/-/g, '_')
.toLowerCase();
}
代码如下:
'helloWorld::ABCDefg'.underscore()
//'helloWorld::ABCDefg'
.replace(/::/g, '/') //'helloWorld/ABCDefg'
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')//helloWorld/ABC_Defg
.replace(/([a-z\d])([A-Z])/g, '$1_$2') //hello_World/ABC_Defg
.replace(/-/g, '_') //hello_World/ABC_Defg
.toLowerCase(); //hello_world/abc_defg
代码如下:
function dasherize() {
return this.replace(/_/g, '-');
}