Get everything after the dash in a string in JavaScript

What would be the cleanest way of doing this that would work in both IE and Firefox?

My string looks like this sometext-20202

Now the sometext and the integer after the dash can be of varying length.

Should I just use substring and index of or are there other ways?

12 thoughts on “Get everything after the dash in a string in JavaScript”

  1. Use a regular expression of the form: \w-\d+ where a \w represents a word and \d represents a digit. They won’t work out of the box, so play around. Try this.

    Reply
  2. var the_string = "sometext-20202";
    var parts = the_string.split('-', 2);
    
    // After calling split(), 'parts' is an array with two elements:
    // parts[0] is 'sometext'
    // parts[1] is '20202'
    
    var the_text = parts[0];
    var the_num  = parts[1];
    
    Reply
  3. You can do it with built-in RegExp(pattern[, flags]) Factory Notation in js like this:

    RegExp(/-(.*)/).exec("sometext-20202")[1]
    

    in above code exec function will return an array with two elements ([“-20202”, “20202”]) one with hyphen(-20202) and one without hyphen(20202) , you should pick second element (index 1)

    Reply
  4. How I would do this:

    // function you can use:
    function getSecondPart(str) {
        return str.split('-')[1];
    }
    // use the function:
    alert(getSecondPart("sometext-20202"));
    
    Reply
  5. You can use split method for it. And if you should take string from specific pattern you can use split with req. exp.:

    var string = "sometext-20202";
    console.log(string.split(/-(.*)/)[1])
    Reply
  6. For those trying to get everything after the first occurance:

    Something like "Nic K Cage" to "K Cage".

    You can use slice to get everything from a certain character. In this case from the first space:

    const delim = " "
    const name = "Nic K Cage"
    
    const end = name.split(delim).slice(1).join(delim) // prints: "K Cage"
    

    Or if OP’s string had two hyphens:

    const text = "sometext-20202-03"
    // Option 1
    const op1 = text.slice(text.indexOf('-')).slice(1) // prints: 20202-03
    // Option 2
    const op2 = text.split('-').slice(1).join("-")     // prints: 20202-03
    
    Reply
  7. I came to this question because I needed what OP was asking but more than what other answers offered (they’re technically correct, but too minimal for my purposes). I’ve made my own solution; maybe it’ll help someone else.

    Let’s say your string is 'Version 12.34.56'. If you use '.' to split, the other answers will tend to give you '56', when maybe what you actually want is '.34.56' (i.e. everything from the first occurrence instead of the last, but OP’s specific case just so happened to only have one occurrence). Perhaps you might even want 'Version 12'.

    I’ve also written this to handle certain failures (like if null gets passed or an empty string, etc.). In those cases, the following function will return false.

    Use

    splitAtSearch('Version 12.34.56', '.') // Returns ['Version 12', '.34.56']
    

    Function

    /**
     * Splits string based on first result in search
     * @param {string} string - String to split
     * @param {string} search - Characters to split at
     * @return {array|false} - Strings, split at search
     *                        False on blank string or invalid type
     */
    function splitAtSearch( string, search ) {
        let isValid = string !== ''              // Disallow Empty
                   && typeof string === 'string' // Allow strings
                   || typeof string === 'number' // Allow numbers
    
        if (!isValid) { return false } // Failed
        else          { string += '' } // Ensure string type
    
        // Search
        let searchIndex = string.indexOf(search)
        let isBlank     = (''+search) === ''
        let isFound     = searchIndex !== -1
        let noSplit     = searchIndex === 0
        let parts       = []
    
        // Remains whole
        if (!isFound || noSplit || isBlank) {
            parts[0] = string
        }
        // Requires splitting
        else {
            parts[0] = string.substring(0, searchIndex)
            parts[1] = string.substring(searchIndex)
        }
    
        return parts
    }
    

    Examples

    splitAtSearch('')                      // false
    splitAtSearch(true)                    // false
    splitAtSearch(false)                   // false
    splitAtSearch(null)                    // false
    splitAtSearch(undefined)               // false
    splitAtSearch(NaN)                     // ['NaN']
    splitAtSearch('foobar', 'ba')          // ['foo', 'bar']
    splitAtSearch('foobar', '')            // ['foobar']
    splitAtSearch('foobar', 'z')           // ['foobar']
    splitAtSearch('foobar', 'foo')         // ['foobar'] not ['', 'foobar']
    splitAtSearch('blah bleh bluh', 'bl')  // ['blah bleh bluh']
    splitAtSearch('blah bleh bluh', 'ble') // ['blah ', 'bleh bluh']
    splitAtSearch('$10.99', '.')           // ['$10', '.99']
    splitAtSearch(3.14159, '.')            // ['3', '.14159']
    
    Reply
  8. Everyone else has posted some perfectly reasonable answers. I took a different direction. Without using split, substring, or indexOf. Works great on i.e. and firefox. Probably works on Netscape too.

    Just a loop and two ifs.

    function getAfterDash(str) {
        var dashed = false;
        var result = "";
        for (var i = 0, len = str.length; i < len; i++) {
            if (dashed) {
                result = result + str[i];
            }
            if (str[i] === '-') {
                dashed = true;
            }
        }
        return result;
    };
    
    console.log(getAfterDash("adfjkl-o812347"));
    

    My solution is performant and handles edge cases.


    The point of the above code was to procrastinate work, please don’t actually use it.

    Reply
  9. AFAIK, both substring() and indexOf() are supported by both Mozilla and IE. However, note that substr() might not be supported on earlier versions of some browsers (esp. Netscape/Opera).

    Your post indicates that you already know how to do it using substring() and indexOf(), so I’m not posting a code sample.

    Reply

Leave a Comment