Uriel
Uriel

Reputation: 206

Match search string with start of words only in a string Javascript

I am trying to implement a search function that when user types into input for a keyword, the list of strings below returns only the results that match only at the starts of a word and not in middle of a word.

For example: Correct: Input: "of" => Output: "Of mice and men" or "mice and of men" Incorrect: "of" => Output: "under the roof" //contains "of"

I have tried 2 unsuccessfull methods

Method 1

let string = "I have often"
if(string.includes('of'))
    console.log('Match') //incorrect

Method 2

let string = "mice and of men"
function startsAt(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}
if(startsAt('of',string))
    console.log('No match') //incorrect because strings starts with "mice"

Basically i need a method that will find only matches at the beginning of any word in a string.

Upvotes: 0

Views: 1227

Answers (2)

Thierry
Thierry

Reputation: 41

Sometimes ago but for regular expression : You can also play with regex-generator

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370679

Use a case-insensitive regular expression that starts with a word boundary:

const pattern = /\bof/i;
console.log(
  pattern.test('Of mice and men'),
  pattern.test('I am under the roof')
);

To construct this from an arbitrary string:

const input = 'of';
const pattern = new RegExp('\\b' + input, 'i');
console.log(
  pattern.test('Of mice and men'),
  pattern.test('I am under the roof')
);

Upvotes: 1

Related Questions