Get everything after the dash in a string in JavaScript

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

How I would do this:

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

Solution 2 - Javascript

A solution I prefer would be:

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

Where slug would be your result

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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"

Solution 6 - Javascript

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.

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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.

Solution 11 - Javascript

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

Solution 12 - Javascript

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.

Solution 13 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmrblahView Question on Stackoverflow
Solution 1 - JavascriptartlungView Answer on Stackoverflow
Solution 2 - JavascriptRyanView Answer on Stackoverflow
Solution 3 - JavascriptKankeView Answer on Stackoverflow
Solution 4 - JavascriptSean BrightView Answer on Stackoverflow
Solution 5 - JavascriptMahyar EkramianView Answer on Stackoverflow
Solution 6 - JavascriptCerebrusView Answer on Stackoverflow
Solution 7 - JavascriptkcsoftView Answer on Stackoverflow
Solution 8 - JavascriptLeon WilliamsView Answer on Stackoverflow
Solution 9 - JavascriptSteveView Answer on Stackoverflow
Solution 10 - JavascriptdirkgentlyView Answer on Stackoverflow
Solution 11 - Javascriptaturan23View Answer on Stackoverflow
Solution 12 - JavascriptaxwrView Answer on Stackoverflow
Solution 13 - JavascriptBhanusri KokalaView Answer on Stackoverflow