开发者

What is inside first <> brackets

开发者 https://www.devze.com 2023-03-01 02:17 出处:网络
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>\';

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

精彩评论

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