views:

51

answers:

1

Hi, i must convert a string (user generated) to a regex rule.

My problem is that i must say,

replace every sign but not a-b, 0-9, minus, dot and comma

I hope somebody can help.

HTML

<div id="d1" class="line1"></div>

JS

$(function() {

    new_regex_rule = 'hello,bl.com,dkd-dkd.com,blub,blib,satssan kommt';

    // new_regex_rule = new_regex_rule.replace(/[a-z][0-9][-.]/gi,'');

    $('#d1').append('<hr />'+new_regex_rule+'<hr />');  

    if(new_regex_rule.match(/\s/)){ new_regex_rule = new_regex_rule.replace(/\s/,'\\s'); }
    if(new_regex_rule.match(/,/)){ new_regex_rule = new_regex_rule.replace(/\,/,'|'); }

    $('#d1').append('<hr />'+new_regex_rule+'<hr />');  
});

working example

http://www.jsfiddle.net/V9Euk/517/

Thanks in advance! Peter

EDIT: Or is ist maybe possible to use the string as regex rule as it is?

+1  A: 

this one replaces every sign but not a-b, 0-9, minus, dot and comma (case sensitive)

var regex = /[^a-z0-9.,]/g
alert("[email protected]?".replace(regex,"X"));
Caspar Kleijne
No need to escape the `.` inside the character set and the `,` anyway.
Gumbo
tested it here it : http://jsfiddle.net/awhVc/
Caspar Kleijne
@Gumbo Thanks for the lesson. This was common behaviour of me, I now know is obsolete ;) fixed it.
Caspar Kleijne
Thank you very much!
Peter