Reputation: 1935
I am relatively new to RegEx and am trying to achieve something which I think may be quite simple for someone more experienced than I.
I would like to construct a snippet in JavaScript which will take an input and strip anything before and including a specific character - in this case, an underscore.
Thus 0_test
, 1_anotherTest
, 2_someOtherTest
would become test
, anotherTest
and someOtherTest
, respectively.
Thanks in advance!
Upvotes: 0
Views: 780
Reputation: 626802
You can use the following regex (which can only be great if your special character is not known, see Alex's solution for just _
):
^[^_]*_
Explanation:
^
- Beginning of a string[^_]*
- Any number of characters other than _
_
- UnderscoreAnd replace with empty string.
var re = /^[^_]*_/;
var str = '1_anotherTest';
var subst = '';
document.getElementById("res").innerHTML = result = str.replace(re, subst);
<div id="res"/>
If you have to match before a digit, and you do not know which digit it can be, then the regex way is better (with the /^[^0-9]*[0-9]/
or /^\D*\d/
regex).
Upvotes: 1
Reputation: 175766
Simply read from its position to the end:
var str = "2_someOtherTest";
var res = str.substr(str.indexOf('_') + 1);
Upvotes: 0