If the idea is to exchange several spaces (from what I understood from replace
which already exists) or several hyphens for a single hyphen, just use replace(/[- ]+/g, "-")
.
To character class [- ]
takes a hyphen or a space, and the quantifier +
takes two or more occurrences. So, if you have more than one space or hyphen, they are exchanged for a single hyphen.
You don’t have to call normalize
twice. The former has already ensured that accents are removed, so the resulting string no longer needs to be normalized again (better understand what normalization is reading here).
$("#titulo").keyup(function(){
var titulo=$(this).val();
titulo = removerAcentos(titulo);
$("#previewalias").html(titulo);
})
function removerAcentos(s) {
return s.normalize('NFD')
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[- ]+/g, "-");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="uk-input uk-form-large" name="titulo" type="text" placeholder="Adicione um título" id="titulo"><br>
<div class="uk-text-muted uk-text-small">Link: <span id="previewalias">/link</span></div>
Although the replace
above also exchanges one hyphen for another, which is somewhat redundant. Then you can switch to swap one or more spaces for a hyphen, and then check for two or more hyphens (and switch to one):
$("#titulo").keyup(function(){
var titulo=$(this).val();
titulo = removerAcentos(titulo);
$("#previewalias").html(titulo);
})
function removerAcentos(s) {
return s.normalize('NFD')
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/ +/g, "-")
.replace(/-{2,}/g, "-");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="uk-input uk-form-large" name="titulo" type="text" placeholder="Adicione um título" id="titulo"><br>
<div class="uk-text-muted uk-text-small">Link: <span id="previewalias">/link</span></div>