28905

How do I perform a Javascript match with a pattern that depends on a variable?

Question:

The current implementation of <a href="http://remysharp.com/2007/12/28/jquery-tag-suggestion/" rel="nofollow">Remy Sharp's jQuery tag suggestion plugin</a> only checks for matches at the beginning of a tag. For example, typing "Photoshop" will not return a tag named "Adobe Photoshop".

By default, the search is case-sensitive. I have slightly modified it to trim excess spaces and ignore case:

for (i = 0; i < tagsToSearch.length; i++) { if (tagsToSearch[i].toLowerCase().indexOf(jQuery.trim(currentTag.tag.toLowerCase())) === 0) { matches.push(tagsToSearch[i]); } }

What I have tried to do is modify this again to be able to return "Adobe Photoshop" when the user types in "Photoshop". I have tried using match, but I can't seem to get it to work when a variable is present in the pattern:

for (i = 0; i < tagsToSearch.length; i++) { var ctag = jQuery.trim(currentTag.tag); if (tagsToSearch[i].match("/" + ctag + "/i")) { // this never matches, presumably because of the variable 'ctag' matches.push(tagsToSearch[i]); } }

What is the correct syntax to perform a regex search in this manner?

Answer1:

If you want to do regex dynamically in JavaScript, you have to use the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp" rel="nofollow">RegExp object</a>. I believe your code would look like this (haven't tested, not sure, but right general idea):

for (i = 0; i < tagsToSearch.length; i++) { var ctag = jQuery.trim(currentTag.tag); var regex = new RegExp(ctag, "i") if (tagsToSearch[i].match(regex)) { matches.push(tagsToSearch[i]); } }

Answer2:

Instead of

"/" + ctag + "/i"

Use

new RegExp(ctag, "i")

Answer3:

You could also continue to use indexOf, just change your === 0 to >= 0:

for (i = 0; i < tagsToSearch.length; i++) { if (tagsToSearch[i].toLowerCase().indexOf(jQuery.trim(currentTag.tag.toLowerCase())) >= 0) { matches.push(tagsToSearch[i]); } }

But then again, I may be wrong.

Recommend

  • Modification history in a file
  • count the occurrences of all the letters in a string PHP
  • Stream webcam via. Wowza streaming server
  • Flex: DataGrid column formatting of numbers
  • Case insensitive search in CQ5 using querybuilder
  • PHP exec response as string?
  • cannot load gems in test environment
  • C# “cannot assign field because it is a foreach iteration variable”
  • Excel 2007: Format of email address from Outlook 2007
  • What is RSL (Runtime shared library ) used for in flash?
  • Updating and removing unique join relationships in CakePHP
  • php show all images in directory and sort by last modified
  • Negating Regex PO BOX
  • Is there a way to call library thread-local init/cleanup on thread creation/destruction?
  • Classic ASP URL Rewriting
  • EF 4.1 DBContext AutoDetectChangesEnabled
  • Efficient User-Agent Regex to find Safari in Python
  • Can my PDF ping my server when it is opened?
  • Declaring variable dynamically in VB.net
  • How do I alternate colors in Flat List (React Native)
  • Google Custom Search with transparent background
  • Insert into database using onclick function
  • What is Eclipse's Declaration View used for?
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • Spray.io: When (not) to use non-blocking route handling?
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • AES padding and writing the ciphertext to a disk file
  • Java applet as stand-alone Windows application?
  • Modifying destination and filename of gulp-svg-sprite
  • Can I make an Android app that runs a web view in Chrome 39?
  • How to make Safari send if-modified-since header?
  • GridView Sorting works once only
  • How to pass list parameters for each object using Spring MVC?
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • retrieve vertices with no linked edge in arangodb
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Setting background image for body element in xhtml (for different monitors and resolutions)
  • Change div Background jquery
  • apache spark aggregate function using min value
  • JaxB to read class hierarchy