mrblah
mrblah

Reputation: 103477

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?

Upvotes: 256

Views: 484901

Answers (14)

Jonathan
Jonathan

Reputation: 1399

Efficient, compact and works in the general case:

s='sometext-20202'
s.slice(s.lastIndexOf('-')+1)

Upvotes: 5

Steve
Steve

Reputation: 4975

For those trying to get everything after the first occurrence:

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 result = 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 opt1 = text.slice(text.indexOf('-')).slice(1) // prints: 20202-03
// Option 2
const opt2 = text.split('-').slice(1).join("-")     // prints: 20202-03

Upvotes: 4

Mahyar Ekramian
Mahyar Ekramian

Reputation: 331

With built-in javascript replace() function and using of regex (/(.*)-/), you can replace the substring before the dash character with empty string (""):

"sometext-20202".replace(/(.*)-/,""); // result --> "20202"

Upvotes: 15

Bhanusri Kokala
Bhanusri Kokala

Reputation: 13

To use any delimiter and get first or second part

  //To divide string using deimeter - here @
  //str: full string that is to be splitted
  //delimeter: like '-'
  //part number: 0 - for string befor delimiter , 1 - string after delimiter
  getPartString(str, delimter, partNumber) {
    return str.split(delimter)[partNumber];
  }

Upvotes: 0

aturan23
aturan23

Reputation: 5380

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])

Upvotes: 2

axwr
axwr

Reputation: 2236

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.

Upvotes: 0

Leon Williams
Leon Williams

Reputation: 764

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']

Upvotes: 4

RPL
RPL

Reputation: 3627

A solution I prefer would be:

const str = 'sometext-20202';
const slug = str.split('-').pop();

Where slug would be your result

Upvotes: 211

kcsoft
kcsoft

Reputation: 2947

myString.split('-').splice(1).join('-')

Upvotes: 10

Kanke
Kanke

Reputation: 2747

var testStr = "sometext-20202"
var splitStr = testStr.substring(testStr.indexOf('-') + 1);

Upvotes: 90

artlung
artlung

Reputation: 34003

How I would do this:

// function you can use:
function getSecondPart(str) {
    return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));

Upvotes: 399

Sean Bright
Sean Bright

Reputation: 120634

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];

Upvotes: 33

Cerebrus
Cerebrus

Reputation: 25775

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.

Upvotes: 7

dirkgently
dirkgently

Reputation: 111120

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.

Upvotes: 1

Related Questions