简体   繁体   中英

How to get substring after last specific character in JavaScript?

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

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)
var str = 'test/category/1';
str.substr(str.length -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";
pre=test/category/;
var res = str.substring(pre.length);

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM