【问题标题】:How to replace full file name with random number?如何用随机数替换完整的文件名?
【发布时间】:2016-06-13 11:34:30
【问题描述】:

这是我的代码

"test.html".replace(/(?=\.[^.]+$)/g, Math.floor((Math.random() * 1000000) + 1))

如何将 test.html 转换为 38475.html 之类的随机 number.html?

【问题讨论】:

标签: javascript regex


【解决方案1】:

如果正则表达式不是强制性的:),那么试试

 Math.floor((Math.random() * 1000000) + 1) + "." + "test.html".split( "." ).pop();

创建一个方法

function randomizeFileName( fileName )
{
   return Math.floor((Math.random() * 1000000) + 1) + "." + fileName.split( "." ).pop();
}

【讨论】:

  • 有什么理由使用 split.pop() 代替 lastIndexOf()?
  • @PavanTeja 没有特别的原因,我只是更喜欢数组方法,因为它们更具可读性和更简洁的使用。
【解决方案2】:

为什么你必须在这里使用正则表达式? 您可以只使用附加实际文件的文件扩展名的随机数。

 var fileName="test.html";

 fileName= Math.floor((Math.random() * 1000000) + 1)+fileName.substr(fileName.lastIndexOf('.'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-25
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    相关资源
    最近更新 更多