Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get substring after last specific character in JavaScript?

Tags:

javascript

I have a string test/category/1. I have to get substring after test/category/. How can I do that?

like image 651
Gogo Avatar asked Jan 20 '16 12:01

Gogo


People also ask

How do you extract a substring after the last occurrence of the delimiter in JavaScript?

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

How do you get the string after last?

To get the value of a string after the last slash, call the substring() method, passing it the index, after the last index of a / character as a parameter. The substring method returns a new string, containing the specified part of the original string.

How do you put a string after a slash?

First, find the last index of ('/') using . lastIndexOf(str) method. Use the . substring() method to get the access the string after last slash.


5 Answers

You can use String.slice with String.lastIndexOf:

var str = 'test/category/1';
str.slice(0, str.lastIndexOf('/') + 1);
// => "test/category/"
str.slice(str.lastIndexOf('/') + 1);
// => 1
like image 126
Pedro Paredes Avatar answered Oct 27 '22 16:10

Pedro Paredes


The actual code will depend on whether you need the full prefix or the last slash. For the last slash only, see Pedro's answer. For the full prefix (and a variable PREFIX):

var PREFIX = "test/category/";
str.substr(str.lastIndexOf(PREFIX) + PREFIX.length);
like image 23
Alexander Pavlov Avatar answered Oct 27 '22 16:10

Alexander Pavlov


You can use below snippet to get that

var str = 'test/category/1/4'
str.substring(str.lastIndexOf('/')+1)
like image 34
Diljohn5741 Avatar answered Oct 27 '22 18:10

Diljohn5741


A more complete compact ES6 function to do the work for you:

const lastPartAfterSign = (str, separator='/') => {
  let result = str.substring(str.lastIndexOf(separator)+1)
  return result != str ? result : false
}

const input = 'test/category/1'

console.log(lastPartAfterSign(input))
//outputs "1"
like image 21
Hexodus Avatar answered Oct 27 '22 18:10

Hexodus


var str = 'test/category/1';
str.substr(str.length -1);
like image 42
Senzo Tshezi Avatar answered Oct 27 '22 18:10

Senzo Tshezi