Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用随机字符替换字符串,同时保留格式_Javascript_Node.js - Fatal编程技术网

Javascript 用随机字符替换字符串,同时保留格式

Javascript 用随机字符替换字符串,同时保留格式,javascript,node.js,Javascript,Node.js,有没有一种简单的方法可以在保留格式的同时替换字符串中的字符?例如,假设我有一个字符串,其中包含一个电话号码111-222-3333 我想将该数字更改为随机生成的数字,但保留原始格式(所有数字和破折号) 因此,随机输出可能类似于:720-190-6542当然,但这取决于您试图维护的格式。大多数都可以通过一个使用。就您的示例而言,这应该起到以下作用: let number = "123-456-7890"; let numRegex = /\d/g; //this regex finds all i

有没有一种简单的方法可以在保留格式的同时替换字符串中的字符?例如,假设我有一个字符串,其中包含一个电话号码111-222-3333

我想将该数字更改为随机生成的数字,但保留原始格式(所有数字和破折号)


因此,随机输出可能类似于:720-190-6542

当然,但这取决于您试图维护的格式。大多数都可以通过一个使用。就您的示例而言,这应该起到以下作用:

let number = "123-456-7890";
let numRegex = /\d/g; //this regex finds all instances of digits
let randomNumber = number.replace(
    numRegex,
  function(oldNum){ //function to choose what to replace found digits with
    return Math.floor(Math.random() * 10); //randomly chooses an int from 0-9 for each replacement
});

console.log(randomNumber); //prints a random phone number

将随机字符串用于数字选项:

const randomstring = require('randomstring');

let randomNumber = randomstring.generate(options = {
      length: 10,
      charset: 'numeric'
    });

String.prototype.splice = function(indx, rem, str) {
   return this.slice(0, indx) + str + this.slice(indx + Math.abs(rem));
};

var result = randomNumber.toString().splice(3,0,"-").splice(7,0,"-");

到目前为止你试过什么?