简体   繁体   English

如何在js中仅使用.match(regEx)获取没有分隔符的内部字符串?

[英]How to get only internal string without delimiter with .match(regEx) in js?

Hello I am trying to parse an xml string with js. 您好,我正在尝试使用js解析xml字符串。 My string is similar to the one below. 我的字符串类似于下面的字符串。 I am using .match() function with regular expressions. 我正在使用.match()函数和正则表达式。

var str='<rate val="xyz"></rate> <rate val="klm"></rate> <rate val="mnp"></rate>';
var result=str.match(/val="(.+?)"/g);

I want to get a result array like: 我想得到一个像这样的结果数组:

 ["xyz","klm","mnp"]

But it gives me as 但这给了我

["rate val="xyz"","rate val="klm"","rate val="mnp""]

How can I get only values without attribute names? 如何仅获取没有属性名称的值?

Instead of messing with regex, you could use a combination of filter and map to get the properties of the elements in to an array as you require: 您可以使用filtermap的组合来将正则表达式弄乱,而无需根据需要将元素的属性获取到数组中:

var str = '<rate val="xyz"></rate> <rate val="klm"></rate> <rate val="mnp"></rate>';
var result = $(str).filter('rate').map(function() {
    return $(this).attr('val');    
}).get();

console.log(result);

Example fiddle 小提琴的例子

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

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