开发者

is it possible in javascript to include other characters in jquery.Trim()

i have a string that might look like one of these and i want to display this string on the page but remove all trailing characters (spaces,开发者_Python百科 commas . )

var string1  =  "test, test1, test2, test3, ";  
var string2  =  "test, test1, test2, test3 ";  
var string3  =  "test, test1, test2, test3";  

if i use jquery.Trim() that will work for string2 and string3 but i want a solution that will remove the trailing comman from string1 as well.

what is the best way to do this in javascript, jquery ??


Internally, jQuery.trim uses two variables:

trimLeft = /^\s+/,
trimRight = /\s+$/,

which is private to the jQuery function so you can't change them (which is a good thing because other code may depend on jQuery.trim working the way it does).

But you can easily make your own trim function with the semantics that you need, even as a jQuery plugin:

// your plugin:
jQuery.trimCommas = function(text) {
    return text == null ?
        "" :
        text.toString().replace(/^[\s,]+|[\s,]+$/g, "");
};

// your code:
var string1 = "test, test1, test2, test3, ";
alert($.trimCommas(string1));

See this fiddle: http://jsfiddle.net/Nwsur/


The easiest way to do this is with regular expressions.

your_string = your_string.replace(/,?\s+$/, "");

If you want to use this everywhere you can update $.trim to take a regular expression in this manner:

(function($){

var old_trim = $.trim;

function trim() {
    switch (arguments.length) {
        case 2:
            throw new Error("Invalid argument." + 
                            " $.trim must be called with either a string" +
                            " or haystack, replacer, replacement");
            break;
        case 3:
            return arguments[0].replace(arguments[1], arguments[2]);
        default:
            return old_trim.call($, arguments);
    }
}

$.trim = trim;

})(jQuery);

This pattern is sometimes called Duck Punching.


var trimmed = "test3, \t\r\n".replace(/[\s,]+$/, "");

This is exactly what regular expressions are good for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜