Mirsad Batilovic
Mirsad Batilovic

Reputation: 441

Javascript replace utf characters in string

I want to after type Title of post automatically take value and create slug. My code works fine with English Latin characters but problem is when I type characters 'čćšđž'. Code replace first type of this characters in string but if character is repeated than is a problem. So, for testing purpose this title 'šžđčćžđš čćšđžčćšđž čćšđžčć ćčšđžšžčćšđ ćčšžčć' is converted to this slug 'szdcc'.

This is my jquery code:

$('input[name=title]').on('blur', function() {
    var slugElement = $('input[name=slug]');

    if(slugElement.val()) {
        return;
    }

    slugElement.val(this.value.toLowerCase().replace('ž', 'z').replace('č','c').replace('š', 's').replace('ć', 'c').replace('đ', 'd').replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, ''));
});

How to solve this problems? Also is it possible to this few characters put in same replace() function?

Upvotes: 0

Views: 1155

Answers (2)

Alex Kudryashev
Alex Kudryashev

Reputation: 9480

Try this:

    function clearText(inp) {
        var wrong = 'čćšđž';
        var right = 'ccsdz';
        var re = new RegExp('[' + wrong + ']', 'ig');
        return inp.replace(re, function (m) { return right.charAt(wrong.indexOf(m)); });
    }

Upvotes: 2

Michael
Michael

Reputation: 532

replace() only replaces the first occurrence unless regex is used with global modifier. You will need to change them all to regular expression.

replace(/ž/g, "z")

As far as I know, it will not be possible to use a single replace() in your case. If you are concerned with chaining a bunch of .replace() together, you might be better off writing some custom code to replace these characters.

var newStr = "";
for (var i = 0; i < str.length; i++) {
  var c = str.charAt(i);
  switch (c) {
    case "ž": newStr += "z"; break;
    default: newStr += c; break;
  }
}

Upvotes: 1

Related Questions