coure2011
coure2011

Reputation: 42404

What is inside first <> brackets

I want to get content inside the first angle brackets in a string, like

str = 'testing <i need this> yes... and <i dont need this>';  
str1 = '<i also need this> where r u?';  

I want 'i need this' from str
'i also need this' from str1

Upvotes: 2

Views: 104

Answers (1)

Matt Greer
Matt Greer

Reputation: 62027

A regex is a good way to do this:

var regex = /<(.*?)>/;
var match = regex.exec(str);
var insideBrackets = match.length > 1 && match[1];

Edit: switched from + to * as it's true the brackets might contain nothing.

Edit2: BIlly is correct, it needs to be non-greedy, otherwise in your first str it will return everything between the first < and the very last >. Thanks BIlly. If it was me I'd probably go with /<([^>]*)>/ to be explicit in what brackets I'm interested in.

Upvotes: 5

Related Questions