How to Remove Part of a String?

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

How do I do that?

The prefix before _ can change.

1

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.

6

Assuming your string always starts with 'test_':

var str = 'test_23';
alert(str.substring('test_'.length));
2

If you want to remove part of string

let str = "try_me";
str.replace("try_", "");
// me

If you want to replace part of string

let str = "try_me";
str.replace("try_", "test_");
// test_me

Easiest way I think is:

var s = yourString.replace(/.*_/g,"_");
2
string = "test_1234";
alert(string.substring(string.indexOf('_')+1));

It even works if the string has no underscore. Try it at

1
Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest