简体   繁体   English

如何在 JavaScript 中的最后一个特定字符之后获取子字符串?

[英]How to get substring after last specific character in JavaScript?

I have a string test/category/1 .我有一个字符串test/category/1 I have to get substring after test/category/ .我必须在test/category/之后获取子字符串。 How can I do that?我怎样才能做到这一点?

You can use String.slice with String.lastIndexOf :您可以将String.sliceString.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.对于最后一个斜线,请参阅 Pedro 的回答。 For the full prefix (and a variable PREFIX):对于完整前缀(和变量 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:一个更完整的紧凑型 ES6 函数来为你完成工作:

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()您可以使用 indexOf() 和 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)):您可以使用 str.substring(indexStart(, indexEnd)):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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