JavaScript中和String相关的一些兼容性不太好的方法
本文由 小茗同学 发表于 2016-08-02 浏览(5313)
最后修改 2016-08-04 标签:string prototype trim javascript startswith endswidth 兼容性 不好

String.prototype.trim

低版本浏览器不支持字符串的trim相关方法,实际使用中考虑兼容性的话可以使用jQuery提供的$.trim()方法,如果项目中没有采用jQuery,可以自己简单写一个,参考jQuery中的实现:

if(!String.prototype.trim)
{
    String.prototype.trim = function()
    {
        return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
    };
}

参考:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

String.prototype.startsWith和endsWith

切记!这2个方法是直到ECMAScript6才开始支持的!如果不支持可以自己写一个:

if (!String.prototype.startsWith)
{
    String.prototype.startsWith = function(searchString, position)
    {
        position = position || 0;
        return this.substr(position, searchString.length) === searchString;
    };
}
if (!String.prototype.endsWith)
{
    String.prototype.endsWith = function(searchString, position)
    {
        var subjectString = this.toString();
        if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length)
        {
            position = subjectString.length;
        }
        position -= searchString.length;
        var lastIndex = subjectString.indexOf(searchString, position);
        return lastIndex !== -1 && lastIndex === position;
    };
}

本代码参考自:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith