0

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 Answers 4

4

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
8
  • 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? Mar 23, 2010 at 19:43
  • String.split is a built in Javascript function that returns an array. Is it possible that you've overridden String.prototype.split somewhere? Mar 23, 2010 at 19:47
  • Well, jQuery is included in this project so maybe it's using the jQuery split? Mar 23, 2010 at 19:48
  • 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? Mar 23, 2010 at 19:53
  • 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? Mar 23, 2010 at 19:59
1

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"
3
  • Fails if the word to replace is the last element in the list.
    – Brian
    Mar 23, 2010 at 19:35
  • 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). Mar 23, 2010 at 19:35
  • 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
    Mar 23, 2010 at 20:07
0

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.

1
  • 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. Mar 23, 2010 at 21:15
0
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"

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.