1

I'm using Google Maps API geocoding to turn an address into a location on the map. I have it set up as:

var address = document.getElementById("address").innerText;

I have my address div set up as

123 candycane lane (br /> north pole, antartica

Whenver I put a
after the first line, the geocoding won't return any results. But when I remove it and have the address as one line, the geocoder works perfectly. I had thought innerText did not account for HTML such as (br />. Is there anyway to make it so it skips over the line break?

Thanks

P.S. I know my line breaks have parantheses at the beginning, but its because my post wasnt recognizing the HTML line break.

golf_nut
  • 431
  • 1
  • 4
  • 16

1 Answers1

2

.innerText does not return a linebreak-tag (br), as you say, but it returns a newline character (\n).

Simple solution (replace it with a blank space):

var address = document.getElementById('address').innerText.replace(/\n/g, ' ');

Edit, .replace() is a method on the string object, which takes a regular expression as a first parameter. The 'g' stands for global, which means it should replace all occurrences of \n. Without it, only the first occurrence would be replaced. The second parameter is the substitute string.

Björn
  • 29,019
  • 9
  • 65
  • 81
  • I understand that \n is the newline character, but can you explain what (/\n/g, ' '), the whole thing means? I'm new to javascript so I'm unsure of what it does. Thanks – golf_nut Dec 09 '10 at 08:06
  • This is a regular expression search and replace. \n means newline, the pattern goes betweeen slashes /like this/, g is a global modifier meaning 'replace every newline with the replacement text', and the last parameter, ' ', is the replacement text. – nc. Dec 09 '10 at 08:09
  • also, when doing something like 'address', can you use "address" or is 'address' best? – golf_nut Dec 09 '10 at 08:49
  • @sukh: In this case it doesn't matter, but see http://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript – Björn Dec 09 '10 at 08:51