StuBlackett :
I'm working with a Postcode Finder and some of the address elements i.e County are returning empty at times as a ", "
I'm looking to strip them from the string to return a more readable address format
Example Data is JSON :
{
"latitude": 53.381130218505859,
"longitude": -1.4663739204406738,
"addresses": [
"Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
"Crucible Theatre, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
"Sheffield Crucible Productions Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
"Sheffield Theatres Crucible Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
"The City Of Sheffield Theatre Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire"
]
}
As you can see there's a lot of commas and spaces directly after with no data in.
How do I go about doing this? My current code is :
$.ajax(
{
type: 'POST',
url: '/address',
dataType: 'json',
data: { _token: token, postcode: postcode},
success: function( data )
{
$('.addresses').html('');
$.each(data, function(k, v)
{
address = v.replace(/\s+/g, ' ');
$('.addresses').append('<option value="">'+ address +'</option>');
})
}
}
)
epascarello :
You can use a regular expression to clean them up.
var str = "Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire"
var cleaned = str.replace(/,(\s,)+/, ',')
console.log(cleaned)