0

I asked for help yesterday on this topic but I need to expand it and add something to the regex. Here's the FIDDLE of what I have so far to get rid of unwanted words in a string but now I need to also replace the non-word characters such as periods, commas, any slashes, stars, etc. How can I add the \W, if that's what I need to use for this? I tried many variations to no success. Please help out...

<input id="search" type="text" value="bone on ^ * () 
  a thing there and an hifi if the offer, of boffin."/>

$("#search").bind('enterKey', function(e){
var search = $('#search')
               .val()
               .replace( /\b(on|a|the|of|in|if|an)\b/ig, '' )
               .replace( /\s+/g, '-' );
alert( 'Replace spaces: ' + search);
});

$('#search').keyup(function(e){
if(e.keyCode == 13){
  $(this).trigger("enterKey");
}
});
denikov
  • 877
  • 2
  • 17
  • 35

1 Answers1

1

If you simply want to remove them, this will do the trick:

$("#search").bind('enterKey', function(e){
    var search = $('#search')
                   .val()
                   .replace(/\b(on|a|the|of|in|if|an)\b|\W/ig, '')
                   .replace(/\s+/g, '-');
    alert( 'Replace spaces: ' + search);
});
$('#search').keyup(function(e){
if(e.keyCode == 13)
{
  $(this).trigger("enterKey");
}
});

If you want to replace all non-word characters with some other character, use this:

$("#search").bind('enterKey', function(e){
    var search = $('#search')
                   .val()
                   .replace(/\b(on|a|the|of|in|if|an)\b/ig, '')
                   .replace(/[^a-zA-Z0-9_ ]/g, '*')
                   .replace(/\s+/g, '-');
    alert( 'Replace spaces: ' + search);
});
$('#search').keyup(function(e){
if(e.keyCode == 13)
{
  $(this).trigger("enterKey");
}
});
Eran Boudjnah
  • 1,228
  • 20
  • 22
  • 1
    Thanks...the second option is exactly what I wanted. I just modified the second replace statement changing '*' to '' so I don't get a whole bunch of dashes, just one. Thanks again! – denikov Dec 28 '13 at 20:45