0

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!

Alex Ryans
  • 1,865
  • 5
  • 23
  • 31

2 Answers2

1

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 _
  • _ - Underscore

And 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).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • However, even if you are new to regex, you should post your own attempts. Please provide them in your question, otherwise, it will be closed, and most probably downvoted. – Wiktor Stribiżew Apr 14 '15 at 12:58
0

Simply read from its position to the end:

var str = "2_someOtherTest";
var res = str.substr(str.indexOf('_') + 1);
Alex K.
  • 171,639
  • 30
  • 264
  • 288