1

I'm trying to match a text string in javascript as long as it isn't a substring of a predefined word.

E.g. let's say we have these words in the file and even if there's a match, I don't want the word blue to show up in the search;

value
lunar
blue
clue

So if the user searches for lu, all the words other than blue should show up. If the user were to search for ue, only value and clue should be matched.

I tried doing a negative look ahead like this;

((?!blue)lu)

Didn't work though and I'm not sure what else to do.

9
  • So if I understand correct, you want clue to be in result, but not blue. Am I right? Commented May 29, 2017 at 12:32
  • 2
    You have to use word boundaries : \blu\b Commented May 29, 2017 at 12:33
  • Request for clarification, I don't want the word blue... then why only word blue? Commented May 29, 2017 at 12:38
  • @revo this was just a simplified example of what I want to do. In any case, I want to know how to do, I don't have anything against the word blue ;) Commented May 29, 2017 at 12:41
  • 2
    See @anubhava's answer. It seems to be a solution to your problem. Commented May 29, 2017 at 12:48

1 Answer 1

7

You need to place \w* to match 0 or more word characters between negative lookahead and your search string.

With lu as search string:

/\b(?!blue)\w*lu\w*/

With ue as search string:

/\b(?!blue)\w*ue\w*/

RegEx Demo

Actual Javascript code can be this:

var kw = "lu"; or "ue"
var re = new RegExp("\\b(?!blue)\\w*" + kw + "\\w*");
Sign up to request clarification or add additional context in comments.

1 Comment

This user has a nasty history of asking questions and not bothering to accepting answers.

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.