Daft
Daft

Reputation: 10964

Remove unwanted part of String. Regex / JS

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?

Upvotes: 9

Views: 32640

Answers (3)

TobyRush
TobyRush

Reputation: 756

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'

Upvotes: 3

Jonny 5
Jonny 5

Reputation: 12389

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;

Upvotes: 18

Amit Joki
Amit Joki

Reputation: 59282

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

Upvotes: 7

Related Questions