zeflex
zeflex

Reputation: 1527

Make Url friendly from string

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

Upvotes: 5

Views: 10228

Answers (3)

ramazandonmez
ramazandonmez

Reputation: 41

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

Upvotes: 1

Arie Xiao
Arie Xiao

Reputation: 14082

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

Upvotes: 6

Mike Samuel
Mike Samuel

Reputation: 120486

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.

Upvotes: 4

Related Questions