简体   繁体   中英

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?

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)); });
    }

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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM