0

I want to get all the words, except one, from a string using JS regex match function. For example, for a string testhello123worldtestWTF, excluding the word test, the result would be helloworldWTF.

I realize that I have to do it using look-ahead functions, but I can't figiure out how exactly. I came up with the following regex (?!test)[a-zA-Z]+(?=.*test), however, it work only partially.

Thom A
  • 88,727
  • 11
  • 45
  • 75
stee1rat
  • 720
  • 2
  • 9
  • 20
  • 2
    Possible duplicate of [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Peter B Jun 26 '17 at 14:58
  • So I noticed your question is strange. You said you want to check for 'test' but in your results you also stripped out the 123 along with the test. Was that a typo? – Stephen Adkins Jun 26 '17 at 15:18
  • By "word" he meant `[a-zA-Z]+`, without digits. – streetturtle Jun 26 '17 at 15:20
  • Please fix your question to be in line with what you have said in comments (like, you want to do a REPLACE, and exactly what the string should look like before and after the replacement). – James Jun 26 '17 at 15:40

4 Answers4

1

IMHO, I would try to replace the incriminated word with an empty string, no?

Dfaure
  • 564
  • 7
  • 26
0

Lookarounds seem to be an overkill for it, you can just replace the test with nothing:

var str = 'testhello123worldtestWTF';
var res = str.replace(/test/g, '');
streetturtle
  • 5,472
  • 2
  • 25
  • 43
  • The problem is that I want to change all found word-occurrences to `word`. So I need to keep the word test in its place. For `testhello123worldtestWTF` my desired end result would be ['test', 'word', 'word', 'test', 'word'] – stee1rat Jun 26 '17 at 15:11
0

Plugging this into your refiddle produces the results you're looking for:

/(test)/g

It matches all occurrences of the word "test" without picking up unwanted words/letters. You can set this to whatever variable you need to hold these.

Kevin
  • 199
  • 8
0

WORDS OF CAUTION

Seeing that you have no set delimiters in your inputted string, I must say that you cannot reliably exclude a specific word - to a certain extent.

For example, if you want to exclude test, this might create a problem if the input was protester or rotatestreet. You don't have clear demarcations of what a word is, thus leading you to exclude test when you might not have meant to.

On the other hand, if you just want to ignore the string test regardless, just replace test with an empty string and you are good to go.

EyuelDK
  • 3,029
  • 2
  • 19
  • 27