---
title: "extjs源码分析-013(String扩展)"
author: "y1d2y3xyz"
date: "2011-03-18T23:05:11Z"
tags: []
categories: ["Web前端"]
slug: "extjs-013-string"
draft: false
lastmod: "2011-03-19T11:56:03Z"
id: 967094
url: "https://lovebeyond.iteye.com/blog/967094"
---

```java

//字符串替换
/*
var cls = 'my-class', text = 'Some text';
var s = String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
*/
Ext.applyIf(String, {
    format : function(format){
        var args = Ext.toArray(arguments, 1);
        return format.replace(/\{(\d+)\}/g, function(m, i){
            return args[i];
        });
    },
    //对字符串中的|\\进行转义输出
    escape : function(string) {
        return string.replace(/('|\\)/g, "\\$1");
    },
    //在字符串val左边插入size-val.length个指定字符串ch,如果ch未定义则默认为" "
    leftPad : function (val, size, ch) {
        var result = String(val);
        if(!ch) {
            ch = " ";
        }
        while (result.length < size) {
            result = ch + result;
        }
        return result;
    },
})


//俩个值切换，调用方式:sort = sort.toggle('ASC', 'DESC');
    String.prototype.toggle = function(value, other){
     return this == value ? other : value;
    };
    //去除字符串的空格 调用方式:var s = '  foo bar  ';_s = s.trim();
    String.prototype.trim = function(){
      var re = /^\s+|\s+$/g;
      return function(){ return this.replace(re, ""); };
    }()


```