Let’s say I have test_23
and I want to remove test_
.
How do I do that?
The prefix before _
can change.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With