21

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

8 Answers 8

43

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
Sign up to request clarification or add additional context in comments.

Comments

8

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);

Comments

5

You can use below snippet to get that

var str = 'test/category/1/4'
str.substring(str.lastIndexOf('/')+1)

Comments

2

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"

Comments

1
var str = 'test/category/1';
str.substr(str.length -1);

Comments

0

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/"))

Comments

0
var str = "test/category/1";
pre=test/category/;
var res = str.substring(pre.length);

Comments

0

You can use str.substring(indexStart(, indexEnd)):

var str = 'test/category/1';
var ln=str.length;
alert(str.substring(ln-1,ln));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.