开发者

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 nee开发者_Go百科d this>';  
str1 = '<i also need this> where r u?';  

I want 'i need this' from str

'i also need this' from str1


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜