Getting the First Word in a Tag With Regex

99封情书 提交于 2020-01-16 11:53:23

问题


I'm trying to make a regex to get the first word in a < ... > tag. I already have one to get all the words in a tag. I'm using this for it:

/<(.*?)>/

My question is, can I get the first word in a tag using a regex?


回答1:


Here's a working solution: /<([^>\s]+)[^>]*>/




回答2:


This will do it...

/<(.*?)\s/



回答3:


In simple case /<(\S+)/ might be what you are looking for, or you might be more formal and actually list only characters allowed in tag names.




回答4:


var tag = "< hello world>";
var regex = /<\s*(\S*)\b/;

if (match_arr = tag.match(regex)) {
  alert("yes:" +  match_arr[1]);
}

is there any way to get every word after the first word in a tag?

var tag = "< hello world goodbye >";
var regex = /<(.*?)>/;

if (match_arr = tag.match(regex)) {
  var str = match_arr[1].trim();
  var words = str.split(" ");
  console.log("-->" + words.slice(1).join(" ") + "<--");
}

--output:--
-->world goodbye<--


来源:https://stackoverflow.com/questions/16290505/getting-the-first-word-in-a-tag-with-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!