void Tricks Logo
void Tricks Logo

JavaScript Substring Custom Function

Code snippet of a custom javascript function that is easier to use than the inbuilt substring function.

  • 312
JavaScript Substring Custom Function

JavaScript Substring()

The substring() function in JavaScript is used to extract a part from a string by passing a start index and an end index.

It may take some time for beginners to understand it so we have written a function that makes the process of extracting particular details from a string easier.

The Function

function substr(str, type){
    var output;
    
    if(type != 'abbr'){
        var o = type.split("_");
        var direction = o[0];
        var n = o[1];
        var type = o[2];
        var l = str.length;
    }
    
    switch (type) {
        case 'char':
            output = (direction == 'first') ? str.substring(0,n) : str.substring(l-n);
            break;
        case 'word':
            var spaces = [];
            for(var i=0; i<l; i++) {
                if (str[i] === " ") spaces.push(i);
            }
            if(direction == 'first'){
                n = (spaces[n-1]) ? spaces[n-1] : l;
                output = str.substring(0,n);
            }else{
                var sl = spaces.length;
                n = (spaces[sl-n]) ? spaces[sl-n] : 0;
                output = str.substring(n);
            }            
            break;
        case 'abbr':
            var matches = str.match(/\b(\w)/g);
            output = matches.join('');
            break;
        default:
            output = str;
            break;
    }

    return output;
}

Example 1

To extract a substring based on character count:

var a = substr('Are you okay?', 'first_7_char');
var b = substr('Are you okay?', 'last_7_char');
console.log(a);
console.log(b);

Output

Are you
u okay?

Example 2

To get a substring based on word count:

var a = substr('Are you okay?', 'first_2_word');
var b = substr('Are you okay?', 'last_2_word');
console.log(a);
console.log(b);

Output

Are you
you okay?

Example 3

To get the first letter of each words in a string:

var a = substr('Search Engine Optimization', 'abbr');
console.log(a);

Output

SEO

Comments (0)

SUBSCRIBE TO OUR NEWSLETTER