I'm trying to achieve this kind of result:
From This is a test to this-is-a-test
But I'd like to implement these rules:
à ç _ è - é ù.For now I'm using this partial solution:
const str = "This is dope";
const result = str.trim().replace(/\s+/g, "-").toLowerCase();
console.log(result) // this-is-dope
But this doesn't solve the whole problem because it doesn't have all the rules I mentioned.
I appreciate any help in this matter!
EDIT: I'm using React, and I need to implement this solution in an input field as follow :
Using the solution from mplungjan :
// state to hold the typed value
const [text, setText] = useState("");
<input
type="text"
onChange={(e) => {
setText(
e.target.value
.trim()
.replace(/^-+|-+$/g, "")
.replace(/[-\s]+/g, "-")
.replace(/[^a-zA-Z0-9\-àç_èéù]/g, "")
.toLowerCase()
);
// unable to type spaces or dashes at all so far
console.log(text);
}}
value={text}
/>
You can use
function App() {
const [text, setText] = React.useState('');
function toKebabCase({ target: { value } }) {
setText( value.replace(/[-\s]+/g, "-").replace(/^-/, '').replace(/[^a-zA-Z0-9àç_èéù-]+/g, "").toLowerCase() )
}
return <div>
Text: <input type='text' onChange={toKebabCase} value={text} />
</div>
}
ReactDOM.render(<App/>, document.querySelector('#root'))
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
The value.replace(/[-\s]+/g, "-").replace(/^-/, '').replace(/[^a-zA-Z0-9àç_èéù-]+/g, "").toLowerCase() will
- (with .replace(/[-\s]+/g, "-")) and then- (with .replace(/^-/, ''))_, -, à, ç, è, é and ù (with .replace(/[^a-zA-Z0-9àç_èéù-]+/g, "")).toLowerCase()).const str = "- This is0 dope $$ !";
const result = str.toLowerCase().replace(/[^0-9a-z ]+/g,'').trim().replace(/\s+/g, '-');
console.log(result)