开发者

javascript fail - regexp bug

开发者 https://www.devze.com 2023-01-24 14:42 出处:网络
Hei all I have this code function prototype( str , id ) { var ret = str; ret = ret.replace( /ø/g, \'oe\' );

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.


You forgot the greedy-modifier

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

....

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


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消