简体   繁体   English

使用Regex从HTML标记属性获取字符串-JavaScript

[英]Use Regex to get string from HTML tag attribute - JavaScript

I am very new to Regex but I think it is the best way to do this. 我是Regex的新手,但我认为这是最好的方法。 I really need to get the text from an HTML tag attribute to an array of strings to be able to work with. 我确实需要将文本从HTML标签属性转换为字符串数组,以便能够使用。 I have multiple <span> tags with an onclick attribute. 我有多个具有onclick属性的<span>标记。 It's the text from within the attribute that I need. 这是我需要的属性中的文本。 I will give you an example. 我举一个例子。

<span class="ord" onclick="top.wiki_ord_klick('abstrakt','icke konkret, ogripbar')">abstrakt</span><br>

This is a span class with an onclick attribute. 这是一个具有onclick属性的span类。 What I want to access is the words in top.wiki_ord_klick(...). 我要访问的是top.wiki_ord_klick(...)中的单词。 I want them to be individually made strings and put into an array. 我希望将它们分别制成字符串并放入数组中。 The result would be 结果将是

var result = ["abstrakt", "icke konkret, ogripbar"];

How can I do this? 我怎样才能做到这一点?

The following uses match() with regular expression /'.+?'/ . 以下将match()与正则表达式/'.+?'/ This matches everything between single quotes (including the quotes), and this returns the parameters as an array. 这会匹配单引号(包括引号)之间的所有内容,并将参数作为数组返回。

It then iterates through the array using map() to remove the single quotes. 然后,使用map()遍历数组以删除单引号。

 var span = document.querySelector('span.ord'), //get the <span> element click = span.onclick.toString(), //get its inline click event as a string parms = click.match(/'.+?'/g); //get an array of the onclick parameters parms = parms.map(function(parm) { return parm.replace(/'/g, ''); //remove single quotes }); console.log(parms); 
 <span class="ord" onclick="top.wiki_ord_klick('abstrakt', 'icke konkret, ogripbar')">abstrakt</span> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM