I have a string test/category/1
. I have to get substring after test/category/
. How can I do that?
Using lastIndexOf and substring : var str = "foo/bar/test. html"; var n = str. lastIndexOf('/'); var result = str. substring(n + 1);
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.
First, find the last index of ('/') using . lastIndexOf(str) method. Use the . substring() method to get the access the string after last slash.
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
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);
You can use below snippet to get that
var str = 'test/category/1/4'
str.substring(str.lastIndexOf('/')+1)
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"
var str = 'test/category/1';
str.substr(str.length -1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With