jQuery Plugin, Plugin jQuery, Projetos » jQuery Plugin stringToSlug
17 de setembro de 2009 por Leo Caseiro
O plugin jQuery stringToSlug serve para criar URL AMIGÁVEIS (SLUG), conhecidas como permalinks.
Download no GitHub (migrado para o GitHub em 26/07/2011)
jquery.stringToSlug.js 1.2.1
jQuery stringToSlug Plugin no GitHub para quem quiser contribuir
Depois de muito pesquisar um Plugin em jQuery que fizesse isso, encontrei muitos que funcionam para outros idiomas. Mas somente para idiomas que não possuem acentuação.
JQUERY SLUG PLUGIN (PT-BR Special Chars Replaces)
JQUERY SIMPLESLUG (PT-BR Special Chars Replaces)
Por isso, fiz questão de estudar as melhores features dos 2 plugins, e obviamente, que funcionasse em Português do Brasil [PT-BR].
Demo
Preview: altere-o-texto-deste-campo
Abaixo, segue a documentação em Inglês, pois pretendo disponibilizar no site da jQuery.
Default Usage:
/**
* Default Events: Blur, KeyUp e KeyDown:
* Default Get Put: #permalink
* Default Space Replacement: - (hiphen)
*/
$(document).ready( function() {
$("#string").stringToSlug();
});
The values Default at Plugin Usage:
$(document).ready( function() {
$("#title").stringToSlug({
setEvents: 'keyup keydown blur',
getPut: '#permalink',
space: '-'
});
});
Other(s) Event(s) Usage:
Para alterar os eventos, devemos inserir 1 ou mais eventos, separados por epaço:
$(document).ready( function() {
//Only Event Blur
$("#only-blur-event").stringToSlug({
setEvents: "blur"
);
//2 Events or More
//This sample, Usage Events: KeyUp and KeyDown
$("#keyup-and-keydown-events").stringToSlug({
setEvents: "keyup keydown"
);
});
Other Get Put Preview Usage:
$(document).ready( function() {
//Previem in all texarea
$("input[name=string]").stringToSlug({
getPut: "textarea"
);
//Preview in all elements preview class
$("#input[name=string]").stringToSlug({
getPut: ".class"
);
});
Replace hiphen by other char Usage:
$(document).ready( function() {
//Replace by underscore
$("#input[name=string]").stringToSlug({
space: "_"
);
});
Dúvidas e/ou sugestões, favor informar nos comentários.
Melhorias na documentação são bem vindas.
Se este plugin é útil para você, por favor dê um feedback votando no site do jQuery:
http://plugins.jquery.com/project/stringToSlug
Versão Server Side em PHP
atualizado em 25 de Julho de 2010
Para visualizar e efetuar o download da Classe em PHP que faz o mesmo que este plugin, acesse o link da Classe StringToSlug PHP
Gostou do Post? Assine o Feed 
Artigos Relacionados:
jquery.stringToSlug.js 1.2.1
[...] você precisa baixar um plugin do jQuery chamado stringToSlug. O Leo Caseiro adaptou esse plugin para tratar palavras com [...]
Nossa brow esse plugin vai ser muito util em um sistema que vou desenvolver
Obrigado
My recent post Chat no site usando GTALK (TALK)
Cool! this is what i was looking for!! Thanks!
My recent post Symfony2 -> Doctrine2 – Twin Tables sharing same Entity possible solution
Ae cara, nao tem como postar uma pagina de exemplo?
Não to conseguindo usar aqui :S
Sou meio novo no uso de jQuery ;(
A própria página serve de demo! Altere o texto da minha caixa de texto e vai perceber.
Utilize o Firebug ou Web Developer que são extensões do Firefox para ajudar na análise do Javascript.
Mas basta seguir os passos do meus exemplos que vai conseguir utilizar o plugin.
Obs: Desculpe a minha demora, mas não estava mais recebendo os comentários do Blog por email.
Abs
[...] yang dibutuhkan ya script jquery dan plugin stringToSlug [...]
Some of the code seems to have got edited out so here is a pastebin http://pastebin.com/UmmpZrLL
I also wanted to point out that this is only really going to be useful when you are using an input field instead of a span. I found it useful when I need to insert the input into a database.
BandonRandon´s last [type] ..Get Involved with WPBook!
BandonRandon´s last [type] ..Get Involved with WPBook!
Thanks for this plugin.
For what it's worth I've modified this script to be able to hide the input of the slug and replace it with a span. I modified the default settings to add `
hide: false,
hideclass: 'stringToSlug'`
then added
`if (defaults.hide) {
jQuery('.stringToSlug').remove();
jQuery('input.' + defaults.getPut).after(""+stringToSlug+"");
jQuery('input.' + defaults.getPut).hide();
}`
This is based largely on Perry Trinier's jQuery Slug Generation Plugin http://www.thewebsitetailor.com/jquery-slug-plugi…
Hope you conceder adding it to the official release or that others find it useful
BandonRandon´s last [type] ..Get Involved with WPBook!
BandonRandon´s last [type] ..Get Involved with WPBook!
Hi, thanks for your idea.
But using a text field of type hidden have StringToSlug work with the plugin.
The other plugin you showed me does not work in my language.
PS: Sorry for the delay. I was no longer receiving messages by email and enable this option only today.
Cara, muito obrigado por esse script, fez o meu dia!
Forte Abraço.
Miguel Couto
Leo,
Obrigado por partilhar esse plugin. A genialidade dele está na simplicidade. (Expressões regulares são ótimas)
Parabéns.
el enlace de descarga no funciona
Ótimo este plugin. Encontrarei vários mas nenhum fazia com perfeição a substituição dos caracteres acentuados.
[...] jQuery Plugin stringToSlug [...]
Existe a possibilidade dele gerar no mesmo campo?
Olá Carlos, obrigado pelos parabéns! Espero que este plugin resolva seus “problemas”.
Existe sim como executar a função no mesmo campo, mas só irá funcionar perfeitamente no Evento Blur, senão ele não deixa dar espaço. Utilize o mesmo id para o seletor e para o getPut, veja o exemplo testado e validado:
Parabéns, eu tava tentando fazer..
Mas o projeto ta atrasado, é melhor eu pegar algo mais consolidado, eu me interesso pela versão Server Side pode me mandar por e-mail? Muito Obrigado!
Vou providenciar a versão Server Side e disponibilizar aqui para Download também.
Ei Leo, eu conheço esse script de algum lugar
hahahaha
Cara parabéns pela integração com o jQuery, ela ficou bem simple pro end user.
Abração
Hi, a little upgrade for win-1250. Some czech letters more. http://www.apollo1.cz/dev/jquery/string-to-slug.j…
Muito bom isso. Já tá no favoritos, vai facilitar tudo por aqui.
abs
.-= Luiz´s last blog ..Pescar pode te deixar mais nervoso do que imagina =-.
Parabens pelo Post excelente alternativa a URls amigáveis, se possivel poderia me enviar tambem a solução server side !!!
Abraços
Olá Leo, realmente o seu plugin é excelente! Tudo o que estava precisando. Você poderia me enviar a solução em server side também?
Muito obrigado.
Guillermo
.-= Guillermo Guerini´s last blog ..Balsamiq Mockups – A simple and powerful tool =-.
Muito bom o problema é estamos utilizando uma função em JS. E se o Js estiver desabilitado? Talvez sirva para o seu caso.
Porém o interessante seria uma função server side em php.
Andei um dia destes estudando o wordpress, e ele sim gera a mesma coisa que você colocou só que em PHP.
Conhece algo parecido em PHP?
Abraço
Olá, Mauro
Com certeza tenho uma alternativa em Server Side.
Vou enviar no seu email, ok?
Pretendo postar aqui no Blog essa alternativa logo mais!
Abs
.-= Leo´s last blog ..jQuery Plugin stringToSlug =-.
Muito bom,
Vai ser uma mão na roda pra todo mundo !
Post salvo no meu delicious [=