How I would do this:

Copy// function you can use:
function getSecondPart(str) {
    return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));
Answer from artlung on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › substring
String.prototype.substring() - JavaScript | MDN
The substring() method swaps its two arguments if indexStart is greater than indexEnd, meaning that a string is still returned.
🌐
W3Schools
w3schools.com › jsref › jsref_substring.asp
JavaScript String substring() Method
Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean · Boolean() new Boolean() constructor prototype toString() valueOf() JS Classes ... new Date() constructor getDate() getDay() getFullYear(
🌐
TutorialsPoint
tutorialspoint.com › how-to-get-a-part-of-string-after-a-specified-character-in-javascript
How to get a part of string after a specified character in JavaScript?
To get a part of a string, string.substring() method is used in javascript. Using this method we can get any part of a string that is before or after a particular character. This method slices a string from a given start index(including) to end index(excluding).
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-get-substring-after-specific-character
Get the Substring after a specific Character in JavaScript | bobbyhadz
JavaScript indexes are zero-based, so the index of the first character in the string is 0 and the index of the last character is str.length - 1. If you have to do this often, define a reusable function. ... Copied!function afterCharacter(string, char) { return string.slice(str.indexOf(char) + 1); } const str = 'abc bobby_hadz.com'; // 👇️ hadz.com console.log(afterCharacter(str, '_')); // 👇️ bobby_hadz.com console.log(afterCharacter(str, ' '));
🌐
Dirask
dirask.com › posts › JavaScript-get-substring-after-word-D9aB2D
JavaScript - get substring after word
get substring after word in · JavaScript. In this example, we use indexOf() method to get the index of a word substring. Then we use slice() to get the substring from index + length index to the end of the text string.
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-string-exercise-22.php
JavaScript validation with regular expression: Get a part of string after a specified character - w3resource
If 'pos' is 'b' (before), it returns the substring after the specified character using 'substring' and 'indexOf' functions. If 'pos' is 'a' (after), it returns the substring before the specified character.
Top answer
1 of 12
385

At least three ways:

A regular expression:

var result = /[^/]*$/.exec("foo/bar/test.html")[0];

...which says "grab the series of characters not containing a slash" ([^/]*) at the end of the string ($). Then it grabs the matched characters from the returned match object by indexing into it ([0]); in a match object, the first entry is the whole matched string. No need for capture groups.

Live example

Using lastIndexOf and substring:

var str = "foo/bar/test.html";
var n = str.lastIndexOf('/');
var result = str.substring(n + 1);

lastIndexOf does what it sounds like it does: It finds the index of the last occurrence of a character (well, string) in a string, returning -1 if not found. Nine times out of ten you probably want to check that return value (if (n !== -1)), but in the above since we're adding 1 to it and calling substring, we'd end up doing str.substring(0) which just returns the string.

Using Array#split

Sudhir and Tom Walters have this covered here and here, but just for completeness:

var parts = "foo/bar/test.html".split("/");
var result = parts[parts.length - 1]; // Or parts.pop();

split splits up a string using the given delimiter, returning an array.

The lastIndexOf / substring solution is probably the most efficient (although one always has to be careful saying anything about JavaScript and performance, since the engines vary so radically from each other), but unless you're doing this thousands of times in a loop, it doesn't matter and I'd strive for clarity of code.

2 of 12
83

Try this:

const url = "files/images/gallery/image.jpg";

console.log(url.split("/").pop());

Find elsewhere
🌐
Sabe
sabe.io › blog › javascript-get-substring-after-specific-character
Get the Substring after a Specific Character in JavaScript
May 10, 2022 - We can use the substring() method to get the substring after the index that we just calculated. JAVASCRIPTconst input = "1) Hello World"; const index = input.indexOf(")"); const substring = input.substring(index + 1); console.log(substring);
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-get-string-after-last-slash
Get the Part after Last Occurrence in a String in JavaScript | bobbyhadz
Copied!function afterLastOccur... the string on each occurrence of the character. Use the String.pop() method to get the part of the string after the last occurrence....
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-index-split-and-manipulate-strings-in-javascript
How To Index, Split, and Manipulate Strings in JavaScript | DigitalOcean
August 24, 2021 - Now that we have a new array in the splitString variable, we can access each section with an index number. ... If an empty parameter is given, split() will create a comma-separated array with each character in the string. By splitting strings you can determine how many words are in a sentence, and use the method as a way to determine people’s first names and last names, for example. The JavaScript trim() method removes white space from both ends of a string, but not anywhere in between.
🌐
SitePoint
sitepoint.com › blog › javascript › quick tip: how to split a string into substrings in javascript
How to Split a String into Substrings in JavaScript — SitePoint
November 6, 2024 - All strings in JavaScript have a substring() method. This method can be used to retrieve a substring at specific indices. substring() accepts two parameters. The first one is required, and indicates the index the substring starts at.
🌐
ReqBin
reqbin.com › code › javascript › i5foejaa › javascript-substring-example
How do I get a substring from a string in JavaScript?
To get a substring from a string in JavaScript, you can use the built-in string.substring(start, end) method. The first parameter specifies the index of the first character from which to get the substring (in JavaScript, indexing starts from zero).
🌐
W3Schools
w3schools.com › jsref › jsref_lastindexof.asp
JavaScript String lastIndexOf() Method
The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-get-value-of-a-string-after-last-slash-in-javascript
How to get value of a string after last slash in JavaScript? | GeeksforGeeks
May 31, 2024 - Below are the approaches used to get the value of a string after the last slash in JavaScript: ... Split the string by .split() method and put it in a variable(array). Use the .length property to get the length of the array.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › lastIndexOf
String.prototype.lastIndexOf() - JavaScript | MDN
const paragraph = "I think Ruth's dog is cuter than your dog!"; const searchTerm = "dog"; console.log( `Index of the last "${searchTerm}" is ${paragraph.lastIndexOf(searchTerm)}`, ); // Expected output: "Index of the last "dog" is 38" ... Substring to search for. All values are coerced to strings, so omitting it or passing undefined causes lastIndexOf() to search for the string "undefined", which is rarely what you want.
🌐
Edureka
edureka.co › blog › javascript-substring
JavaScript Substring() | How is it different from substr() & slice()? | Edureka
January 9, 2025 - The substring() is an inbuilt function in JavaScript which returns a part of the given string from start index to end index. The indexing starts from zero. It is used to return a portion of the string, starting at the specified index and extending ...