• Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 63
  • Last Modified:

Extract text using javascript from within a div?

Would someone please tell me how to extract the street address, city, state, and postal code from within this HTML div using javascript into 4 separate variables?

<div class="address">
123. Broadway
<br>
New York, NY  10009
</div>

var streetAddress = "";
var city = "";
etc, etc.

Thanks in advance for any help
0
Westside2004
Asked:
Westside2004
2 Solutions
 
leakim971PluritechnicianCommented:
test page : https://jsfiddle.net/c9grsf4u/
jQuery(function($) {
	var addresses = []; // we store all in an array
	$(".address").each(function(i,v) {
  	var html = $(this).html().replace(/\n|\r/g, "");
  	var twoLines = html.split("<br>");
    var line1 = twoLines[0];
    var line2 = twoLines[1];
    var cityandpc = line2.split(",");
		var streetAddress = line1;
		var city = cityandpc[0];
    var postalcode = cityandpc[1].split(" ")[3];
    var address = {
    	"streetAddress": streetAddress,
      "city": city,
      "postalcode" : postalcode
    };
    addresses.push(address);
	});
  $("#ta").val(JSON.stringify(addresses)); // for testing we display the array in a textarea
});

Open in new window

0
 
Leonidas DosasCommented:
<!DOCTYPE html>

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div class="address">123. Broadway 
<br>
New York, NY  10009
</div>
        
        <script>
            var elm=document.getElementsByClassName('address')[0].innerHTML;
            
            elm=elm.replace('<br>','');
            elm=elm.split(' ');            
            var street=elm[0]+elm[1];
            var city=elm[2].replace(/\s/g, '')+elm[3].replace(',','');            
            var cityShort=elm[4];
            var postalCode=elm[6];
            console.log(street);
            console.log(city);
            console.log(cityShort);
            console.log(postalCode);
            
        </script>
    </body>
</html>

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now