MtnManChris
MtnManChris

Reputation: 536

how to combine regEx expressions

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 <>

Upvotes: 0

Views: 118

Answers (3)

Daniel Arechiga
Daniel Arechiga

Reputation: 967

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

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

Upvotes: 1

Ravi Sankar Raju
Ravi Sankar Raju

Reputation: 2950

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');

Upvotes: 0

Washington Guedes
Washington Guedes

Reputation: 4365

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.

Upvotes: 2

Related Questions