prasanth sadhana prasanth sadhana - 7 months ago 26
Javascript Question

how to convert text from input to regexp?

One regexp function is below:-



$(document).ready(function(){
$('button').click(function(){
var str = 'abcdefghijklmnopqrstuvwxyz';
var spl = str.match(/input/g);//input text are applied
$('#demo').text(spl);
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id="text">
<button>call</button>
<p id="demo"></p>




how to convert text from input to regexp?
eg:

input k out k;
input y out y;


Thanks in advance...

Answer

You have to get the input value and then use the javascript RegExp object where you can put the input value in the constructor.

Here's what you need :

$(document).ready(function(){
  $('button').click(function(){
    var str = 'abcdefghijklmnopqrstuvwxyz';
    var inputValue = $("#text").val();
    var spl = str.match(new RegExp(inputValue));
    $('#demo').text(spl);
  });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id="text">
<button>call</button>
<p id="demo"></p>