How to Match a Whole Word in JavaScript

How can I match a whole word in JavaScript?

To use a dynamic regular expression see my updated code:

new RegExp("\\b" + lookup + "\\b").test(textbox.value)

Your specific example is backwards:

alert((/\b(2)\b/g).test(lookup));

Regexpal

Regex Object

Javascript reg ex to match whole word only, bound only by whitespace

You can try: \sBlah\s.

Or if you allow beginning and end anchors, (^|\s)Blah(\s|$)

This will match "Blah" by itself, or each Blah in "Blah and Blah"

See also

  • regular-expressions.info/Character classes and Anchors

    • \s stands for "whitespace character".
    • The caret ^ matches the position before the first character in the string
    • Similarly, $ matches right after the last character in the string

Lookahead variant

If you want to match both Blah in "Blah Blah", then since the one space is "shared" between the two occurrences, you must use assertions. Something like:

(^|\s)Blah(?=\s|$)

See also

  • regular-expressions.info/Lookarounds

Capturing only Blah

The above regex would also match the leading whitespace.

If you want only Blah, ideally, lookbehind would've been nice:

(?<=^|\s)Blah(?=\s|$)

But since Javascript doesn't support it, you can instead write:

(?:^|\s)(Blah)(?=\s|$)

Now Blah would be captured in \1, with no leading whitespace.

See also

  • regular-expressions.info/Grouping and flavor comparison

How to match a whole word or sentence after a specific character with regexp

Here are 2 options depending on whether you want to include the colon in the pattern that you are capturing.

  • with the colon
    ^:\w*
  • with a lookback for the colon
    (?<=^:)\w*

    This will match a word after the colon.

    You may want any number of any character .* or any combination of word characters and spaces `[\w\s]*

Check for whole and exact word match

You can use regular expression (\bregExp\b) to find the exact match of the word.

The \b metacharacter is used to find a match at the beginning or end of a word.

let speech = "you ever looked at someone";

let a = "look";

if(new RegExp("\\b"+a+"\\b").test(speech)){

console.log("Whole Word Matches")

} else {

console.log("No Match!")

}

Match and replace whole words in javascript

You can use the word boundary \b, so \bwant\b. Do keep in mind that the regex definition of a word may not suit you, though. Javascript regex defines word boundaries as the place between a word character \w, which is [a-zA-Z0-9_] and a non-word character (everything except that).

References

  • regular-expressions.info/Word boundaries

Examples of word boundary caveats

  • There's a \bcan\b in "can't" (because ' is not a \w)
  • There's no \blove\b in "love_me"(because e and _ are both \w)

Matching whole words that start or end with special characters

The \b word boundary construct is ambiguous. You need to use unambiguous constructs that will make sure there are non-word chars or start/end of string to the left/right of the word matched.

You may use

/(?:^|\W)\?FOO\?(?!\w)/g

Here, (?:^|\W) is a non-capturing group that matches either the start of a string or any non-word char, a char other than an ASCII letter, digit and _. (?!\w) is a negative lookahead that fails the match if, immediately to the right of the current location, there is a word char.

Or, with ECMAScript 2018 compatible JS environments,

/(?<!\w)\?FOO\?(?!\w)/g

See this regex demo.

The (?<!\w) is a negative lookbehind that fails the match if there is a word char immediately to the left of the current location.

In code, you may use it directly with String#match to extract all occurrences, like s.match(/(?<!\w)\?FOO\?(?!\w)/g).

The first expression needs a capturing group around the word you need to extract:

var strs = ["?FOO is cool", "I love ?FOO", "FOO is cool", "FOO?is cool", "aaFOO?is cool"];
var rx = /(?:^|\W)(\?FOO)(?!\w)/g;
for (var s of strs) {
var res = [], m;
while (m=rx.exec(s)) {
res.push(m[1]);
}
console.log(s, "=>", res);
}

Search for a whole word in a string

You could use regular expressions:

\bhow\b

Example:

/\bhow\b/i.test(searchOnstring);

If you want to have a variable word (e.g. from a user input), you have to pay attention to not include special RegExp characters.

You have to escape them, for example with the function provided in the MDN (scroll down a bit):

function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

var regex = '\\b';
regex += escapeRegExp(yourDynamicString);
regex += '\\b';

new RegExp(regex, "i").test(searchOnstring);


Related Topics



Leave a reply



Submit