Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 915
NullVoxPopuli Avatar asked Aug 25 '10 18:08

NullVoxPopuli


People also ask

How do I remove a specific part of a string?

To remove a substring from a string, call the replace() method, passing it the substring and an empty string as parameters, e.g. str. replace("example", "") . The replace() method will return a new string, where the first occurrence of the supplied substring is removed.

How do you delete a particular part of a string in Java?

replace() Method to Remove Substring in Java The first and most commonly used method to remove/replace any substring is the replace() method of Java String class. The first parameter is the substring to be replaced, and the second parameter is the new substring to replace the first parameter.


1 Answers

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.

like image 185
Andy E Avatar answered Sep 30 '22 07:09

Andy E