JavaScript String – How to Remove Part of a String

javascriptstring

Let’s say I have test_23 and I want to remove test_.

How do I do that?

The prefix before _ can change.

Best Answer

My favourite way of doing this is "splitting and popping":

var str = "test_23";
alert(str.split("_").pop());
// -> 23

var str2 = "adifferenttest_153";
alert(str2.split("_").pop());
// -> 153

split() splits a string into an array of strings using a specified separator string.
pop() removes the last element from an array and returns that element.

Related Question