0

How can I make a function to convert a string to lower-case and replace all spaces with dashes?

Examples:

If the input is "Hello World", the output should be "hello-world".

If the input is "Merhaba Dünya", the output should be "merhaba-dunya".

This is what I have tried so far.

<input name="Title" type="text" class="form-control" placeholder="Title">
<input name="TitleSeo" type="text" class="form-control" placeholder="Title">
function create_seo_url($baslik = "") {
    $TR = array('ç', 'Ç', 'ı', 'İ', 'ş', 'Ş', 'ğ', 'Ğ', 'ö', 'Ö', 'ü', 'Ü');
    $EN = array('c', 'c', 'i', 'i', 's', 's', 'g', 'g', 'o', 'o', 'u', 'u');
    $baslik = str_replace($TR, $EN, $baslik);
    $baslik = mb_strtolower($baslik, 'UTF-8');
    $baslik = preg_replace('#[^-a-zA-Z0-9_ ]#', '', $baslik);
    $baslik = trim($baslik);
    $baslik = preg_replace('#[-_ ]+#', '-', $baslik);
    return $baslik;
}
  • Similar question: http://stackoverflow.com/questions/5519368/how-can-i-perform-a-str-replace-in-javascript-replacing-text-in-javascript – Wédney Yuri Jun 13 '15 at 11:24

2 Answers2

1

You can use this code on the @humble.rumble code:

function transformCharacters(text) {
    return String(text)
        .replace(/ç/gi, 'c')
        .replace(/[ıİ]/gi, 'i')
        .replace(/[ş]/gi, 's')
        .replace(/[ğ]/gi, 'g')
        .replace(/[ö]/gi, 'o')
        .replace(/[ş]/gi, 's')
        .replace(/[ü]/gi, 'u')
        .replace(/[ü]/gi, 'u')
        .replace(/[-_ ]/g, '-')
        .replace(/[^-a-zA-Z0-9_ ]/g, '')
        .toLowerCase();
}
Wédney Yuri
  • 1,267
  • 12
  • 21
  • And bamm!! You are awesome too :) I've combined your answer with @humble.rumble 's answer and that is what i need! :) –  Jun 12 '15 at 23:40
  • 1
    There is no need to use the `String` constructor if what is being passed in is already a string. `text.replace(/ç/gi, 'c')` would work. – Useless Code Jun 13 '15 at 05:52
0

Select each input.

Assign an onkeyup handler to the first input which uses String.toLowerCase().replace(/ /g,'-'); to make the words lower case and replace the spaces with dashes.

Then apply the new value to the second input

var title = document.querySelector('input[name="Title"]');
var titleSeo = document.querySelector('input[name="TitleSeo"]');
title.onkeyup = function() {
  titleSeo.value = this.value.toLowerCase().replace(/ /g, '-');
}
<form action="" method="post" id="myForm">
  <input name="Title" type="text" class="form-control" placeholder="Title">
  <input name="TitleSeo" type="text" class="form-control" placeholder="Title">
  <input type="submit" value="Submit">
</form>