开发者

Splitting html tags in jquery

开发者 https://www.devze.com 2023-03-26 11:53 出处:网络
How would I split this value in jquery. I was going to use the split function but thought there might be an easier way.

How would I split this value in jquery. I was going to use the split function but thought there might be an easier way.

var location = <span class="title">Greenbeck</span><br>9th Street<br>2554 glockcove<br>State, OX 10025<a class="loc" href="#" title="More info">Click For More Info</a>

I want to split it so I get this result. Greenbeck 9th Street glockcove State, OX 10025

I was going to use split like this. var spl = location.split('

'开发者_开发知识库, location.length); And then split it again using and then again with a and so on but it seems like there is a n easier an more efficient way.


as suggested map is the right way to filter and join and you need .contents() to retrieve even text nodes, so :

var plainAddress = $('<div>'+location+'</div>').contents().map(function(){
    var e = $(this);
    return (e.is('a') || e.is('br')) ? null : e.text();
}).get().join(' ');
// ouptput : 'Greenbeck 9th Street 2554 glockcove State, OX 10025'

be carefull with remove or detach because they modify the dom tree, it is different than filter a collection result...


You can try:

 var location = $('<div><span class="title">Greenbeck</span><br>9th Street<br>2554 glockcove<br>State, OX 10025<a class="loc" href="#" title="More info">Click For More Info</a></div>');
location.find('a.loc').detach();
console.log(location.text());


It's actually much easier if you do it in jQuery:

Assuming that location is a string, you can instantly turn it into a jquery object: $(location)

Now that it is an object, you can iterate through each one: $(location).each()

Or you can map it into an object or array: myArr = $(location).map()

Example: http://jsfiddle.net/rkw79/yZaAm/

Keep in mind that you have to strip out blank elements


$('selector').text() give the inside plain text of element, so you may try to wrap and text (didn't try) :

var plainAddress = $('<div>'+location+'</div>').text();


Start with a smidgen of raw Javascript and follow up with jQuery:

  1. .replace() the <br>s with spaces
  2. .append() the string to a DIV to make using jQuery on it easy.
  3. .remove() those pesky A tags from the context of your jQuery object.
  4. Show just the .text()

.

var $html, result, location = '...';

$html = $("<div></div>").append(location.replace(/<br>/gi, " "));
$("a", $html).remove();
result = $html.text();

Working example

0

精彩评论

暂无评论...
验证码 换一张
取 消