1

What I want is simple. I have an input field and I want to check what items from an unordered list (ul) contain the input's value.

So, I have this:

$('input#search').keyup(
    function() {
        var value = $(this).val();
        if (value.length > 0) {
            var patt = /value/g;
            console.log(patt);
            $('ul#list li').filter(function() {
                return (patt.test($(this).html()));
            });
        }
     }
);

My problem here is that if, for example, the value of the input is 'abcd' patt will be /value/g instead of /abcd/g so I want to know how can I insert the value in the pattern.

Vikram Deshmukh
  • 12,304
  • 4
  • 36
  • 38
ali
  • 10,927
  • 20
  • 89
  • 138

2 Answers2

0

define patt as new RegExp

var patt = new RegExp(value,"g")
Sergei Zahharenko
  • 1,514
  • 12
  • 16
0

To create a pattern based on dynamic data you'd use the RegExp ctor passing it a string of the pattern. e.g.

var word = 'foo';
var re = new RegExp(word, 'g'); // var re = /foo/g

Don't forget to escape characters with special meaning in regexp.

However, if you're just looking for a simple "is x within y" comparison, indexOf can perform this check very quickly:

var sample = 'this is a foo sentence';
var loc = 'Hello, world!'.indexOf('world') // 7

then simply check if indexOf(...) != -1.

Community
  • 1
  • 1
Brad Christie
  • 100,477
  • 16
  • 156
  • 200