2016-11-17 7 views
0

現在、私は文字列を少し並べ替えようとしています。私は.mapを使用してこれを行う必要があると信じています。文字列を並べ替える必要があります。乱数を表すN合計ゲームオーバー/アンダーNを設定します。これは、marketのvarに格納されます。これは、Under/Over N Total Games Set Nに並べ替える必要があります。私は多くの面倒なif文を使用し、substrを使用してこれをやり始めましたが、これは素晴らしいコードではありません。とにかく素晴らしい解決策。私はこれを行うためのより良い方法があるかどうか疑問に思った。文字列内の各単語を並べ替えるようにマップする

文字列の場合、各marketLabelはわずかに異なりますが、数字(N)は毎回異なる可能性がありますが、これが役立つ場合、最大数Nは5になります。分のコードで

賢明これは私が持っているものです。

Set 1 Total Games Over/Under 9.5 
Set 2 Total Games Over/Under 9.5 
Set 3 Total Games Over/Under 9.5 
Set 4 Total Games Over/Under 9.5 
Set 5 Total Games Over/Under 9.5 

再する:

if (marketLabel.includes('Set' && 'Total Games Over/Under')) { 
    var splits = 'foo'; // = marketLabel.split('/'); 
    var set = 'foo'; 
    var market = 'foo'; 
    if(marketLabel.includes('Set 1')) { 
    var arr = marketLabel.split(" ").map(function (val) { 
     console.log(String(val)); 
     return String(val) + 1; 
    }); 
    } 
    if(marketLabel.includes('Set 2')) { 
    splits = marketLabel.split('Set 2'); 
    set = marketLabel.substr(0, marketLabel.indexOf('2')+1); 
    return "Under/Over" + splits + " " + set; 
    } 
    if(marketLabel.includes('Set 3')) { 
    splits = marketLabel.split('Set 3'); 
    set = "set 3"; 
    console.log('foo 3'); 
    } 
    if(marketLabel.includes('Set 4')) { 
    set = "set 4" 
    splits = marketLabel.split('Set 4'); 
    console.log('foo 4'); 
    } 
    if(marketLabel.includes('Set 5')) { 
    set = "set 5" 
    splits = marketLabel.split('Set 1'); 
    console.log('foo 5'); 
    } 

だから要約すると、私は必要なものを、次のいずれかの可能性がありmarketLabelです-orderedへ:

Under/Over 9.5 Total Games Set 1 
Under/Over 9.5 Total Games Set 2 
Under/Over 9.5 Total Games Set 3 
Under/Over 9.5 Total Games Set 4 
Under/Over 9.5 Total Games Set 5 
+1

あなたが投稿する必要がありますあなたのコード - 私はあなたが求めていることを本当に理解できません。 –

答えて

1

Uging正規表現:

market = "Set 1 Total Games Over/Under 9.5"; 
 
regex = /Set ([0-9.]+) Total Games (Over)\/(Under) ([0-9.]+)/ 
 
var match = regex.exec(market); 
 
var newStr = match[3] + '/' + match[2] + ' ' + match[1] + ' Total Games Set ' + match[4]; 
 
console.log(newStr);

番号、OverUnder文字列がキャプチャされ、match配列要素を印刷することによって並べ替えられています。

スキーマは、言葉よりも優れている:

enter image description here

また、数字だけをキャプチャし、正しい順序で文字列にそれらを注入することができます

market = "Set 1 Total Games Over/Under 9.5"; 
 
regex = /Set ([0-9.]+) Total Games Over\/Under ([0-9.]+)/ 
 
var match = regex.exec(market); 
 
var newStr = 'Under/Over ' + match[1] + ' Total Games Set ' + match[2]; 
 
console.log(newStr);

+0

これで 'return ['Under/Over%s Total Games Set%s'、match [2]、match [1]] 'を使ってブラウザに正しくレンダリングされましたが、実際の'%s'はブラウザ。 – DaveDavidson

+0

文字列と配列要素を連結した 'newStr'変数セットを追加するように編集しました。 – SLePort

関連する問題