0

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?

2 Answers 2

2

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)); });
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks for quick answer. I'm gonna try this and reply to you soon. Is it possible to this five characters čćšđž put in one replace() regular expression?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.