6

For example I have this string:

make no@ sen# `se !

I would to generate url like this

make-no-sen-se!

I have this:

    var value = $('.titleVal').val();
    if (value != '') {
        value = value.replace(/[^a-z0-9 _-]/gi, '-').toLowerCase();

        value = value.split(' ');
        var result = '';

        for (var i = 0; i < value.length; i++) {
            if ((value.length - 1) == i) {
                result += value[i];
            } else {
                result += value[i] + '-';
            }
        }
        $('#vidUrl').val(result);
    }

But it generate this:

make-no--sen---se--
1
  • Maybe just follow that with a regex that collapses multiples of - to just one. Commented Mar 11, 2014 at 14:52

3 Answers 3

6

Use the + or * to represent repeated occurance of a set.

function process(value) {
    return value == undefined ? '' : value.replace(/[^a-z0-9_]+/gi, '-').replace(/^-|-$/g, '').toLowerCase();
}

var result = process($('.titleVal').val());
$('#vidUrl').val(result);
Sign up to request clarification or add additional context in comments.

Comments

4
value = value.replace(/[^a-z0-9 _-]/gi, '-').toLowerCase();

should probably be

value = encodeURIComponent(value.toLowerCase().replace(/[^a-z0-9 _-]+/gi, '-'));

Calling toLowerCase before doing the replace will make sure that Latin upper-case letters are not replaced with dashes.

The '+' after the character set will convert sequences of multiple characters like '@ ' to a single dash.

The encodeURIComponent call will ensure that the result is safe to include in a URL path component.

You might also want to look into expanding the set of letters and digits that you do not replace with dashes so that the result is more friendly to non-Western-European users.

Comments

1

try this:

var value = "-make no@ sen# `se !";
if (value != "") {
    value = value.replace(/[^a-z0-9]/g, '-')
                 .replace(/\-{2,}/g, '-')
                 .toLowerCase();
    if(value.indexOf("-", 1) != -1)
        value = value.substring(1);

    if(value.indexOf("-", value.length -1) != -1)
        value = value.substring(0,value.length - 1);

    console.log(value);
}

Comments

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.