這個問題在這里已經有了答案: 如何在每次出現時用隨機值替換正則運算式? (2 個回答) 昨天關門。
這是我的代碼:
let str = 'I am NUMBER years old. My friend is NUMBER years old'
str = str.replace(/NUMBER/g, Math.floor(Math.random() * 10))
console.log(str) // possible result: 'I am 6 years old. My friend is 6 years old'
有什么方法可以在使用 string.replace() 的同時每個都有亂數嗎?(即“我 8 歲。我的朋友 3 歲”)
uj5u.com熱心網友回復:
replace可以將替換函式作為第二個引數...
let str = 'I am NUMBER years old. My friend is NUMBER years old'
str = str.replace(/NUMBER/g, () => Math.floor(Math.random() * 10))
console.log(str) // possible result: 'I am 6 years old. My friend is 6 years old'
uj5u.com熱心網友回復:
您可以使用模板文字:
const randomAge = () => Math.floor(Math.random() * 10);
const str = `I am ${randomAge()} years old. My friend is ${randomAge()} years old.`;
console.log(str);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457115.html
標籤:javascript 正则表达式
上一篇:具有特定標準問題的正則運算式
