Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
Replace white space with a dash using javascript inside a hyperlink?

I'm trying to format a bunch of auto generated links containing white spaces, into versions where the white spaces have been replaced by "-" (dash) like this:

<a id="replacewhitespace" href="/properties-for-sale in Los Angeles">Los Angeles</a>

Changed into:

<a id="replacewhitespace" href="/properties-for-sale-in-Los-Angeles">Los Angeles</a>

The white space breaks the links.

I'm quite new to javascript, and been trying a bunch of stuff from researching online, but i can't seem to find a way to target the "href" part of a link. Up until now i managed to put the following together, but it only changes "normal" text (seen in the front-end). I need to target the html/href part.

var orignalstring = document.getElementById("replacewhitespace").innerHTML;
var newstring = orignalstring.replace("","-");
document.getElementById("replacewhitespace").innerHTML = newstring;
<li><span class="property-type">Penthouses</span> for sale in <span id="property-area"><a id="replacewhitespace" href="/properties-for-sale in Los Angeles">Los Angeles</a></span></li>

Can anyone help/guide me in the right direction?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You'll have to first decode the anchor's target (accessed via the href property) with decodeURI, then use replaceAll:

var orignalstring = document.getElementById("replacewhitespace").href;
var newstring = decodeURI(orignalstring).replaceAll(" ","-");
document.getElementById("replacewhitespace").href = newstring;

console.log(newstring)
<li><span class="property-type">Penthouses</span> for sale in <span id="property-area"><a id="replacewhitespace" href="/properties-for-sale in Los Angeles">Los Angeles</a></span></li>

Or more simply:

var elem = document.getElementById("replacewhitespace");
elem.href = elem.href.replaceAll("%20", "-")

console.log(elem.href)
<li><span class="property-type">Penthouses</span> for sale in <span id="property-area"><a id="replacewhitespace" href="/properties-for-sale in Los Angeles">Los Angeles</a></span></li>

If you have multiple links, you can do:

document.querySelectorAll("a[href*=' ']").forEach(e => {
  e.href = e.href.replaceAll("%20", "-");
  console.log(e.href)
})
<li><span class="property-type">Penthouses</span> for sale in <span id="property-area">'
<a id="replacewhitespace" href="/properties-for-sale in Los Angeles">Los Angeles</a>
<a id="replacewhitespace" href="/properties-for-sale in Los Angeles">Los Angeles</a>
</span></li>

about 4 years ago · Juan Pablo Isaza Relatório

0

  • You don't need to modify the innerHTML, just use Element.getAttribute and Element.setAttribute
  • Use String.prototype.replaceAll or String.prototype.replace using the Global g flag for the RegExp part
  • Find all your elements with space inside a href attribute by using the Attribute [href*=' '] selector:

const elsHrefWithSpaces = document.querySelectorAll("[href*=' ']");

elsHrefWithSpaces.forEach(el => {
  el.setAttribute("href", el.getAttribute("href").replace(/ /g, "-"));
});
<a id="replacewhitespace" href="/properties-for-sale in Los Angeles">Los Angeles</a>  
<br>
<a id="replacewhitespace" href="/some spaces here">Los Spaces</a>

about 4 years ago · Juan Pablo Isaza Relatório

0

Thanks guys!

Just as the answers were coming in, i managed to do it this way by a little (!!! - spend 2 hours prior to this :-D ) tampering around in JSFiddle:

function replace() {
    var aEl = document.getElementById('replacewhitespace');
    aEl.href = aEl.href.replaceAll('%20', '-');
}


replace();
<a id="replacewhitespace" href="/penthouses for sale in Los Angeles">Los Angeles</a>

Works in the JSFiddle at least - i guess this will do the trick (?!).

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda