简体   繁体   中英

How to remove the comma(,) from the first position and last position of string

I want to remove the comma(,) from the the string if it occur at first position or last position in the string.

For Example :

 var str = ",abcd,efg,last,";

The output should be

output = 'abcd,efg,last'

if input is

str = "abcdef,ghij,kl"

the output should be :

output = "abcdef,ghij,kl"
var str = ",abcd,efg,last,";
var res = str.replace(/^,|,$/g, '');
console.log(res);

do this

this will remove the comma if it is at the starting position or at the end of the string position

There must be some strip() function in Javascript that I don't know for lack of my knowledge. But here is how you can do it using regex:

 output = ",abcd,efg,last,".replace(/^,|,$/g, "");

JavaScript doesn't include a native method for this. The closest is trim , but that doesn't take any args. I think it should, though. So you could write something like this

String.prototype.trim = (function (trim) {
    if (!trim) // polyfill if not included in browser
        trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        };
    else if (trim.call('.', '.') === '') // already supports this
        return trim;
    return function (chars) {
        if (!chars) return trim.call(this);
        chars = chars.replace(/([\^\\\]-])/g, '\\$1');
        return this.replace(new RegExp('^['+chars+']+|['+chars+']+$', 'g'), '');
    }
}(String.prototype.trim));

Now we have

'   foo   '.trim();    // "foo"
',,,foo,,,'.trim(','); // "foo"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM