Reputation: 603
I have a string test/category/1
. I have to get substring after test/category/
. How can I do that?
Upvotes: 21
Views: 37326
Reputation: 12927
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"
Upvotes: 2
Reputation: 1
You can use str.substring(indexStart(, indexEnd)):
var str = 'test/category/1';
var ln=str.length;
alert(str.substring(ln-1,ln));
Upvotes: 0
Reputation: 2466
var str = "test/category/1";
pre=test/category/;
var res = str.substring(pre.length);
Upvotes: 0
Reputation: 434
You can use below snippet to get that
var str = 'test/category/1/4'
str.substring(str.lastIndexOf('/')+1)
Upvotes: 5
Reputation: 3390
You can use the indexOf() and slice()
function after(str, substr) {
return str.slice(str.indexOf(substr) + substr.length, str.length);
}
// Test:
document.write(after("test/category/1", "test/category/"))
Upvotes: 0
Reputation: 32286
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);
Upvotes: 8
Reputation: 750
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
Upvotes: 43