Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get everything after the dash in a string in JavaScript

Tags:

javascript

How I would do this:

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

A solution I prefer would be:

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

Where slug would be your result


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

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

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.


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"

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