本文介绍了jQuery以字符串格式在标记内部抓取文本并添加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串就像

 Lorem Ipsum is simply dummy text of the printing and typesetting
 industry.<grab> First Item</grab>Lorem Ipsum is simply dummy text of
 the printing and typesetting industry.<grab>Second Item</grab>Lorem
 Ipsum is simply dummy text of the printing and typesetting
 industry.<grab>Third Item</grab>Lorem Ipsum is simply dummy text of
 the printing and typesetting industry.

现在我需要获取< grab>之间的所有文字。 ..< / grab> 标记并添加两个数组。我尝试了这个,但它没有通过

now I need to grab all text between the <grab>....</grab> tags and add them two an array. I tried this but it didnt go through

var data = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab> First Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab>Second Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab>Third Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.';

var array = $('<grab>').map(function() {
  return $(this).text();
}).get();
$('body').append(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

你能告诉我怎么做吗

推荐答案

实际上这些不是DOM元素,因此可能正则表达式会帮助你。

Those are not DOM elements actually, so probably regex would help you.

var data = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab> First Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab>Second Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab>Third Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.';
var r = /<grab>(.*?)<\/grab>/g;
var grabs = data.match(r).map(function(x){
   return x.replace(r,'$1');
});
console.log(grabs);

这篇关于jQuery以字符串格式在标记内部抓取文本并添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 15:11