Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace "<br>↵" with commas in javascript array

Tags:

I get the following symbol when I print my array to console: "<br>↵"

How do I replace all instances of "<br>↵" with commas in a JS array?

e.g.

["767 5th Ave<br>↵New York, NY 10153, USA", "677 5th Ave<br>↵New York, NY 10022, USA"]

to

["767 5th Ave, New York, NY 10153, USA", "677 5th Ave, New York, NY 10022, USA"]

The value is taken from:

<address class="main">
  <p>767 5th Ave<br>
  New York, NY 10153, USA</p>
</address>

with the following code:

$("address.main p:not(:empty)").each(function() {
  addresses_google[0].push( $(this).html() );
});
like image 363
Pim Avatar asked Dec 05 '16 23:12

Pim


1 Answers

var addresses = ["767 5th Ave<br>↵New York, NY 10153, USA", "677 5th Ave<br>↵New York, NY 10022, USA"];

var formattedAddresses = addresses.map(function(str) {
  return str.replace(/<br>\u21b5/g, ", ");
});

console.log(formattedAddresses);

Update:

It appears that there's html being pushed into this array with line breaks (interpreted as ↵ symbols, used to visualize a newline) vs. plain string literals.

$("address.main p:not(:empty)").each(function() { 
  addresses_google[0].push( $(this).html() );
});

Now that we know this is the result of a loop, we could do this all within that loop's code block without the need of even creating a new array:

$("address.main p:not(:empty)").each(function() {
  var breaks = /<br>(\r\n|\n|\r)/gm;
  var formattedHTML = this.innerHTML.replace(breaks, ', ');

  addresses_google[0].push(formattedHTML);
});
like image 101
Carl Edwards Avatar answered Sep 26 '22 01:09

Carl Edwards