views:

150

answers:

4

I have a string which is basically a list of "words" delimited by commas. These "words" can be pretty much any character e.g. "Bart Simpson, Ex-girlfriend, dude, radical"

I'm trying to use javascript, jQuery, whatever i can to replace a word based on a search string with nothing (in essence, removing the word from the list).

For example, the function is defined as such: function removeWord(myString, wordToReplace) {...};

So, passing the string listed above as myString and passing "dude" as wordToReplace would return the string "Bart Simpson, Ex-girlfriend, radical"

Here's the line of code I was tinkering around with...please help me figure out what's wrong with it or some alternative (better) solution:
$myString.val($myString.val().replace(/wordToReplace\, /, ""));

+4  A: 

Using regular expressions the way you are is not really necessary. Instead I'd split the string into tokens and remove the token that matches the search word, if one does:

function removeWord(myString, wordToReplace)
{
    var tokens = myString.split(/\s*,\s*/);  // allow for whitespace around the comma
    var index = $.inArray(wordToReplace, tokens);  

    if (index != -1)
    {
        tokens.splice(index, 1);
    }

    return tokens.join(", "); // Assumes you want a space after each comma
}

var s = "Bart Simpson, Ex-girlfriend, dude, radical";
removeWord(s, "dude"); // returns "Bart Simpson, Ex-girlfriend, radical

If it is possible for the string that you want to search to contain duplicate items, you can use this altered version of the function (indexOf only returns the first index, so a loop is needed to find all of them):

function removeWord(myString, wordToReplace)
{
    var tokens = myString.split(/\s*,\s*/);
    var index;

    while ((index = $.inArray(wordToReplace, tokens)) != -1)
    {
        tokens.splice(index, 1);
    }

    return tokens.join(", ");
}

var s = "Bart Simpson, Ex-girlfriend, dude, radical, dude";
removeWord(s, "dude"); // returns "Bart Simpson, Ex-girlfriend, radical
Daniel Vandersluis
When I run this code I get a "Object doesn't support this property or method" error on the call to indexOf. When I alert(tokens) it returns the string with the spaces removed. It's like split isn't returning an array? Can i specify the type to force it to return one? Cast it somehow?
YourMomzThaBomb
`String.split` is a built in Javascript function that returns an array. Is it possible that you've overridden `String.prototype.split` somewhere?
Daniel Vandersluis
Well, jQuery is included in this project so maybe it's using the jQuery split?
YourMomzThaBomb
What version of jQuery are you using? I tried it with 1.3.2 and it works. jQuery doesn't define its own String.split as far as I know. Does the output of `alert(String.split)` include `[native code]` (in firefox) or a function definition?
Daniel Vandersluis
I checked in Firefox and yes it does return [native code], however, this is blowing up over in IE7. Does IE7 have problems with indexOf?
YourMomzThaBomb
If you're using jQuery, it comes with `jQuery.inArray`, which does what `Array.prototype.indexOf` does, but also works in IE.
bcherry
@bcherry thanks, I'm not too familiar with jQuery. I've updated my answer to use `jQuery.inArray` instead of `Array.indexOf`.
Daniel Vandersluis
I'm running into problems with this solution in IE7. For some reason using jQuery trim function will not get rid of all trailing whitespace! So when the function evaluates the indexOf for the word, it does not find it (because of the extra space at the end). Any ideas?
YourMomzThaBomb
+1  A: 

Not built for robustness, but this does what you want.

function removeWord(myString, wordToReplace)
 {
    return myString.replace(wordToReplace+", ", "");
 };

 var s = "Bart Simpson, Ex-girlfriend, dude, radical" ; 
 s = removeWord(s, "dude") ; // "Bart Simpson, Ex-girlfriend, radical"
brainjam
Fails if the word to replace is the last element in the list.
Brian
Two problems with this: firstly, it won't match the last item in the list because it will not have a comma after it; secondly, it'll match a substring (for instance, if the list contains 'goodbye' and the word to replace is 'bye', it'll catch the bye in goodbye).
Daniel Vandersluis
I agree. Daniel's solution is better. However, the asker wanted to know what was wrong their code, and this was the simplest way of getting their code to work (with a disclaimer that it was not yet robust).
brainjam
A: 

If you still want to use a regex, you may try this:

function removeWordFromList(str, word) {
    return str.replace(
        new RegExp("(^|,\\s*)" + escape(word) + "(\\s*,\\s*|$)", "g"),
        "$1") // remove the word
      .replace(/\s*,\s*$/, ""); // remove the trailing comma
}

Still, splitting the string into an array is more intuitive and better if you want to manipulate your list.

Chris
I'm running into problems with this solution in IE7. For some reason using jQuery trim function will not get rid of all trailing whitespace! So this function will never match the word passed in because of the trailing space...works well in Firefox tho.
YourMomzThaBomb
A: 
var text = ",Bart Simpson ,, ,  Ex-girlfriend, 5 dude ,radical, sth,, dolr, ";

function removeWord(source, word)
{
  return source
    // replace multiple delimiters into one
    .replace(/\s*,[\s*,]*/g, ', ')
    // trim delimiters
    .replace(/^,\s*|,\s*$/g, '')
    // replaces the substring
    .replace( new RegExp('(^|,\\s)'+word+'($|,\\s)'), function(match, left, right) {
      left = left.trim(), right = right.trim();
      return (left+right).length !== (left.length || right.length) ? ', ': '';
    });
}

removeWord(text,'5 dude');

Should bring something like that

"Bart Simpson, Ex-girlfriend, radical, sth, dolr"
shfx