3

I'm making a faker plugin ( jQuery-Faker ) in jQuery which generates fake data for fill in the form corresponding to their field name. So I want to generate phone number using regular expression /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/ So is there any way to do this?

2 Answers 2

6

You might want to look at the string from regex family of libraries.

Here is the one for javascript

As seen in 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(); // =>
Sign up to request clarification or add additional context in comments.

Comments

4

Try utilizing 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.