9

If I have a string which looks like this:

var myString = '73gf9y::-8auhTHIS_IS_WHAT_I_WANT'

What regex would I need to end up with:

'THIS_IS_WHAT_I_WANT'

The first part of my String will always be a random assortment of characters. Is there some regex which will remove everything up to THIS?

8
  • @anubhava Nope. Upper or lower. I don't mind. Commented Feb 5, 2015 at 14:53
  • has the random part a fixed length? Commented Feb 5, 2015 at 14:57
  • @micha no, no fixed length. Commented Feb 5, 2015 at 14:57
  • @Daft What is the pattern of the texts you want to remove and the texts you want to keep? If the texts you want to keep all CAPS and separated by _? What is the separator of the "to keep" texts and the "to remove" texts? Commented Feb 5, 2015 at 14:57
  • 1
    Only an oracle can help you then. Commented Feb 5, 2015 at 14:57

3 Answers 3

18

So you want to strip out everything from beginning to the first uppercase letter?

console.log(myString.replace(/^[^A-Z]+/,""));

THIS_IS_WHAT_I_WANT

See fiddle, well I'm not sure if that is what you want :)


To strip out everything from start to the first occuring uppercase string, that's followed by _ try:

myString.replace(/^.*?(?=[A-Z]+_)/,"");

This uses a lookahead. See Test at regex101;

Sign up to request clarification or add additional context in comments.

Comments

7

Going by the input, you can use match. The character class [A-Z_] matches any capital letters and _ (Underscore) and + quantifier along with $ anchor matches the character class till the end of the string.

myString = myString.match(/[A-Z_]+$/)[0];
console.log(myString); // THIS_IS_WHAT_I_WANT

2 Comments

Sorry, what will that expression give me back?
@Daft it will give you THIS_IS_WHAT_I_WANT
3

Adding to Amit Joki's excellent solution (sorry I don't have the rep yet to comment): since match returns an array of results, if you need to remove unwanted characters from within the string, you can use join:

input = '(800) 555-1212';
result = input.match(/[0-9]+/g).join('');
console.log(result); // '8005551212'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.