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");
}
});
3
  • Add easier to add: \.\-\[\]\(\).. no? Commented Dec 28, 2013 at 20:29
  • 1
    Or you could filter /[^A-Za-z0-9]/ Commented Dec 28, 2013 at 20:29
  • 1
    It looks like you may be trying to generate a URL-friendly slug from user input. If so, perhaps you could look at how StackOverflow does it? Commented Dec 28, 2013 at 20:36

1 Answer 1

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");
}
});
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.