DaveDev
DaveDev

Reputation: 42225

How to create a regular expression to find a substring within a larger string?

If I have a string, e.g.: "Consensus IRIS 2010-11 Series 6"

If someone types part of that string, e.g. "iris" into a textbox, how can I identify the substring in the original string?

I have the following, but it only matches when the string starts with the value from the text box.

var txt= $('#txtName').val();

var regExp = new RegExp("^" + txt, "i");

var t = item.name.replace(regExp, "<span class='matched-text'>" + txt + "</span>");

Side note: I am baffled by regular expressions!

Upvotes: 1

Views: 118

Answers (3)

Corey Ogburn
Corey Ogburn

Reputation: 24769

Because your regular expression begins with ^ it will only match sequences that begin with whatever the value of txt is. Remove the ^ and you're set.

Upvotes: 2

murgatroid99
murgatroid99

Reputation: 20297

Your problem comes from the fact that prepending "^" to your regular expression makes it only match at the beginning of the string/text box. Remove that and it should work as expected for normal substrings.

However, if someone types a regular expression into the search box, your code could have unexpected effects. For example, if someone typed in \w, every letter and number would be highlighted. This site is good for learning more about regular expressions.

Upvotes: 2

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99919

Try with this:

var regExp = new RegExp(txt, "i");

Or this:

var regExp = new RegExp("\b"+txt"\b", "i");

The first will match txt anywhere in the string, even in the middle of a word. The second will not match in the middle of a word.

Upvotes: 0

Related Questions