How to Get String after Last / in Javascript?

13-Apr-2023

.

Admin

How to Get String after Last / in Javascript?

This article will give you example of how to get string after last / in javascript?. step by step explain get value of a string after last slash in javascript. you will learn how to get value of a string after last slash in javascript?. I’m going to show you about how to get string after last slash in javascript?. Alright, let’s dive into the steps.

You can use the `split()` method to split the string by `/` and then get the last item in the resulting array using the `pop()` method. Here's an example:

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Get String after Last / in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const url = "https://example.com/path/to/file.html";

const parts = url.split("/");

const filename = parts.pop(); // "file.html"

</script>

</html>

Alternatively, you can use a regular expression to match everything after the last `/` in the string:

Example 2:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Get String after Last / in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const url = "https://example.com/path/to/file.html";

const filename = url.match(/\/([^\/]+)$/)[1]; // "file.html"

</script>

</html>

This regex matches a `/` followed by one or more non-`/` characters (`[^\/]+`) at the end of the string (`$`). The parentheses capture this part of the string as a group, which we can access using `[1]`.

#JavaScript