다음을 통해 공유


JavaScript: String.Split with StringSplitOptions, Array removeEntries

 

You would have used String.Split in C# a lot of times and would have appreciated options available like StringSplitOptions.

image

Sometimes, we need similar split options in JavaScript as well. I have written this utility method which you can use  I have extended JavaScript “String” class using string prototype to add this method in all your string variables.

String.prototype.splitWithStringSplitOptions = function (splitBy, removeItemString) {
            if (this == "") {
                return new Array();
            }
            var items = this.split(splitBy);

            for (var i = 0; i < items.length; i++) {
                if (items[i] == removeItemString) {
                    items.splice(i, 1);
                    i--;
                }
            }
            return items;
        }

You can call this methods below. This call removes empty string items from the array.

function UseStringSplitter() {
    var value = "a,b,,c,,d";
    var array = value.splitWithStringSplitOptions(",", "");
    console.log(value);
}

Alternatively, following method can also be used to remove specific items from any JavaScript array

     Array.prototype.IgnoreItems = function (ignoreItem) {
         if (this.length < 1) {
             return this;
         }

         for (var i = 0; i < this.length; i++) {
             if (this[i] == ignoreItem) {
                 this.splice(i, 1);
                 i--;
             }
         }
         return this;
     }

 

Calling above methods with below parameters removes item “a” from the array.

function RemoveItemsFromArray() {
            var value = "a,b,d,a,m";
            var array = value.split(",");
            array.removeEntries("a");
            console.log(value);
        }

Hope this helps. Happy Coding!

Thanks

Gaurav