0

私は文字列を持っています

var stringP= "hi".rand(1,10)." my".rand(10,100)."name is ".rand(23,54).rand(1,4)

パターンは

rand(from,to)

取得する必要があります

hi5 my54name is 335

そのようなものを使用することは可能ですか?

stringP.replace(/rand(*,*)/g, function(match){
    return match.replace(rand(*,*),Math.floor(Math.random() * (to - from + 1) + from));
});
4

2 に答える 2

3

はい、ほぼすべて可能です。それでも、[one!] 適切な正規表現と適切な置換関数を使用する必要があります。

stringP.replace(/rand\((\d+),(\d+)\)/g, function(match, from, to) {
    from = parseInt(from, 10);
    to = parseInt(to, 10);
    return Math.floor(Math.random() * (to - from + 1) + from);
});
于 2013-01-30T23:52:17.330 に答える
2

なぜ正規表現でこれを行うのですか?関数呼び出しはより理にかなっています。

function rand (to, from) {
    return Math.floor(Math.random() * (to - from + 1) + from).toString();
}

var stringP= "hi" + rand(1,10) + " my" + rand(10,100) + "name is " + rand(23,54) + rand(1,4);
于 2013-01-30T23:52:32.097 に答える