Skip to content

Instantly share code, notes, and snippets.

@chrisgrande
Last active April 17, 2021 07:45
Show Gist options
  • Save chrisgrande/0aba5487d6091111501f0b5d02ec6fd0 to your computer and use it in GitHub Desktop.
Save chrisgrande/0aba5487d6091111501f0b5d02ec6fd0 to your computer and use it in GitHub Desktop.
Generic slugify Stimulus controller. Takes input text and outputs slugified version as you type to another input field.
<div data-controller="slugify">
<input data-slugify-target="input" data-action="input->slugify#inputToOutput" type="text">
<input data-slugify-target="output" type="text">
</div>
import { Controller } from 'stimulus'
const slugify = text =>
text
.toString()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.trim()
.replace(/\s+/g, '-')
.replace(/[^\w-]+/g, '')
.replace(/--+/g, '-')
export default class extends Controller {
static get targets() {
return ["input", "output"]
}
inputToOutput() {
this.outputTarget.value = slugify(this.inputTarget.value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment