Gogo
Gogo

Reputation: 603

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?

Upvotes: 21

Views: 37326

Answers (8)

Hexodus
Hexodus

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

Senzo Tshezi
Senzo Tshezi

Reputation: 21

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

Upvotes: 1

Arup Das
Arup Das

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

Roli Agrawal
Roli Agrawal

Reputation: 2466

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

Upvotes: 0

Diljohn5741
Diljohn5741

Reputation: 434

You can use below snippet to get that

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

Upvotes: 5

Goblinlord
Goblinlord

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

Alexander Pavlov
Alexander Pavlov

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

Pedro Paredes
Pedro Paredes

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

Related Questions