ParisNakitaKejser
ParisNakitaKejser

Reputation: 14859

javascript fail - regexp bug

Hei all

I have this code

function prototype( str , id )
{
    var ret = str;

    ret = ret.replace( /ø/g, 'oe' );
    ret = ret.replace( /Ø/g, 'OE' );
    ret = ret.replace( /å/g, 'aa' );
    ret = ret.replace( /Å/g, 'AA' );
    ret = ret.replace( /æ/g, 'ae' );
    ret = ret.replace( /Æ/g, 'AE' );

    document.getElementById( id ).value = ret.replace(/[^a-zA-Z0-9\/\_-]/i,'_').replace(/_+/g,'_');
}

My problem is now, if i use word like this (demo demo demo) its okay make this word to (demo_demo demo)

i use this function to escape urls. the next i need its send it to lower case, after I'm done, i hope for help :)

tanks a lot all.

Upvotes: 0

Views: 505

Answers (4)

fcalderan
fcalderan

Reputation:

The main potential issue I see, is on first replacement (on Ø and other scandinavian characters).

you should change with unicode char representation, e.g. this statement

ret = ret.replace( /Ø/g, 'OE' );

should be

ret = ret.replace( /\u0153/g, 'OE' );

for other diacritic signs just find a unicode chart like http://www.chucke.com/entities.html

Upvotes: 0

Chinmayee G
Chinmayee G

Reputation: 8117

Assuming that your 1st requirement is to replace space, +, - characters with underscore,

document.getElementById( id ).value = ret.replace(/[^a-zA-Z0-9\/\_-]/ig,'_').replace(/_+/ig,'_');

Other requirement is to make it lowercase string

document.getElementById( id ).value = document.getElementById( id ).value.toLowerCase();

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

If the problem is that only the first space gets replaced with _, then you need to put the g option to the regex replace.

ret.replace(/[^a-zA-Z0-9\/\_-]/gi,'_')

to turn the string to lower case use the

toLowerCase() method of strings.

Upvotes: 2

Dr.Molle
Dr.Molle

Reputation: 117334

You forgot the greedy-modifier

/[^a-zA-Z0-9\/\_-]/i

....

/[^a-zA-Z0-9\/\_-]/ig

Upvotes: 2

Related Questions