Generate string to use regular expression in Javascript

I am creating a faker ( jQuery-Faker ) plugin in jQuery that generates fake form data to match their field name, So I want to generate a phone number using regex /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

So is there a way to do this?

+3


source to share


2 answers


You might want to look at a line from the regular expression library family.

Here is for javascript



As you can see from the README , you can do

var RandExp = require('randexp');
var phoneGenerator = new RandExp(/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/);
phoneGenerator.gen(); // =>

      

+6


source


Try to use String.prototype.replace()



var n = "01234567890".split("")
, ph = "nnn-nnn-nnnn".replace(/n/g, function() {
  var i = Math.floor(Math.random() * n.length);
  return n.slice(i, i + 1)[0]
});
document.write(ph);
      

Run codeHide result


+3


source







All Articles