Improving the Search for Name with exact matches using the match() function?


#1

Hi guys,

I got the search text thing working finally! Phew! But now i'm trying to improve on it using the match() function. I'm not sure why this isn't working. How do pass a var into the match( ) function? Is my syntax correct? Thanks guys!

var text = "Hi my name is Sanny. I'm gonna be starting a solo project soon but I'm not entirely sure if I'll call it Sanny yet. My friends say I should call in Sanny or SVelo though! Do think Sanny is a good name for a band?";

var name = "Sanny";
var found = text.match(name);

console.log("You're name appeared" + " " + found + " " + "times");

#2

Hi,

match Method

Matches a string with a regular expression, and returns an array containing the results of that search.

var text = "Hi my name is Sanny. I'm gonna be starting a solo project soon but I'm not entirely sure if I'll call it Sanny yet. My friends say I should call in Sanny or SVelo though! Do think Sanny is a good name for a band?";

var name = "Sanny"; // its a string
var reg = new RegExp(name, 'g'); // we make from "name" a regular expression 
// 'g' stands for global you get more than one hit
// if you want your search not case sensitive use 'g' and 'i'  looks so 'gi'   
var found = text.match(reg); // search the regular expression in "text" 

console.log("You're name appeared" + " " + found.length + " " + "times");

#3

Thanks for that mate! That clears it up for me :slight_smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.