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\, /, ""));
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:
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 (
indexOfonly returns the first index, so a loop is needed to find all of them):