0

How do I take each of these and combine them into a single regEx expression?

var t = "<test>";
t = t.replace(/^</, '');
t = t.replace(/>+$/, '');

which results in t equal to test without the <>

1
  • Use the "or" operator |?
    – HamZa
    May 25, 2016 at 22:08

3 Answers 3

2

You can use pipe |. In regex it means OR:

t = "<test>>".replace(/^<|>+$/g, "");
// "test"

But of course, you can use another ways like:

t = "<test>>".replace(/[<>]/g, "");
// "test"

or even with match:

t = "<test>>".match(/\w+/)[0];
// "test"

Make sure you've added the g-global flag when needed. This flag stands for all occurrences.

1
  • the first one is what I was looking for and I had tried it but did not have the global flag hence it only replaced the first < May 25, 2016 at 22:12
1

If I understand correctly you only want to replace beginning '<' symbols and ending '>' symbols, try this one [>$^<]

var t = "<test>";
t = t.replace('/[>$^<]/', '');
3
  • 1
    this doesn't work. First off it is not a regular expression so it is going to look to replace the string literal '[>$^<]' with ''. Secondly if I make is a regular expression it only replace the < not the > May 25, 2016 at 22:10
  • Actually this will work if you add the g for the global flag... t=t.replace(/[>$^<]/g,''); May 25, 2016 at 22:14
  • Oh yes, sorry I used quotes instead of slash, check my updated answer May 25, 2016 at 22:15
0

Try this

t = t.replace(/^</, '').replace(/>+$/, '');

If you want it in single line, use | to combine the regex.. Like this

t = t.replace(/^<|>+$/g, "");

or capture groups like this

t = t.replace(/^<(.*)>+$/g, '$1');
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.