简体   繁体   English

从像 html 这样的字符串中提取文本值

[英]extract text values from a string like html

I have this string (not html but string ):我有这个string (不是html而是string ):

<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>

Need to extract text value of rTag so result should be a new string:需要提取rTag文本值,所以结果应该是一个新字符串:

ATINA,BELMOPAN,DAMASK,FILIPINI,BANGKOK

Any help?有什么帮助吗?

This will set the content of #output to the new str, but you can do whatever you want after its joined.这会将#output 的内容设置为新的str,但是您可以在加入后做任何您想做的事情。

 var str = []; var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>'; var $html = $($.parseHTML("<div>" + content + "</div>")); $html.find(".rTag").each(function(){ str.push($(this).html()); }); $("#output").html(str.join(","));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <div id="output"></div>

Parsing an HTML string into a DOM element so that it can be processed by javascript/jquery is a fairly standard process:将 HTML 字符串解析为 DOM 元素以便它可以被 javascript/jquery 处理是一个相当标准的过程:

$(content)

will suffice without needing to add it to the DOM (and all that entails behind the scenes).无需将其添加到 DOM(以及幕后需要的所有内容)就足够了。

In this case:在这种情况下:

 var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>'; var arr = $(content).filter(".rTag").map(function() { return $(this).text(); }).get(); console.log(arr.join(","));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

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