0

I know there are many questions answered with this title but I have not found any that fit what I'm looking for...

I need to use regex like this "/^ user input $/i" The user input can put the * regex character in front of or behind the text.

If I use the "new RegExp(user input, "i")" does not accomplish the requirements of ^ and $ and the user regex character *.

I had something like this:

var foo = {User input};

var arr = ['Lorem Ipsum', 'simply dummy text', 'nothing'];

arr = arr.filter(function(item){
     return /^{foo content here}$/i.test(item);
});

Tests:

foo = "Lorem" -> array[]
foo = "Lorem*" -> array['Lorem Ipsum']
foo = "Dummy" -> array[]
foo = "*Dummy*" -> array['simply dummy text']
foo = "*" -> array['Lorem Ipsum', 'simply dummy text', 'nothing']

Many thanks.

1 Answers1

0

You can use '^' + foo + '$', but you should prevent invalid regular expressions as a result. Something like:

var arr = ['Lorem Ipsum', 'simply dummy text', 'nothing'];

function userInput(foo) {
  var re = null;
  try { 
    re = /[*+.]/.test(foo) 
      ? RegExp(foo, 'i') 
      : RegExp('^' + foo + '$', 'i'); }
  catch(err) { 
    return '<i style="color:red">' + err.message +'</i>'; 
  }
  var filtered = arr.filter(function(item){ return re.test(item); });
  return filtered.length 
    ? '<b style="color:green">[' + filtered.join() + ']</b>' 
    : '<b style="color:orange">*nothing found*</b>'
}

document.querySelector('#result').innerHTML =
  'Lorem -> ' + userInput('Lorem') + '\n' +
  'Lorem* -> ' + userInput('Lorem*') + '\n' +
  '*Lorem* -> ' + userInput('*Lorem*') + '\n' +
  'Dummy -> ' + userInput('Dummy') + '\n' +
  '*Dummy.* -> ' + userInput('*Dummy.*') + '\n' +
  '.*Dummy -> ' + userInput('.*Dummy') + '\n' +
  '* -> ' + userInput('*') + '\n' +
  '+ -> ' + userInput('+') + '\n' +
  'd.+ -> ' + userInput('d.+') + '\n' +
  'ips.+$ ->' + userInput('ips.+$') + '\n' +
  'ip.m ->' + userInput('ip.m') + '\n' +
  'i*mp ->' + userInput('i*mp') + '\n' +
  '.* -> ' + userInput('.*');
<pre id=result></pre>
KooiInc
  • 119,216
  • 31
  • 141
  • 177