2016-11-17 40 views
0

目前我正在嘗試重新排序我的字符串。我相信我需要這樣做我使用.map所以,我需要重新排序字符串Set N Total Games Over/Under N. N代表一個隨機數。這存儲在market的變量中。這將需要重新排序N/N總遊戲集N.我已經開始通過使用很多凌亂的if語句,並使用substr來做到這一點,但這不是一個好的解決方案,因爲我的代碼看起來非常混亂,而不是反正很好的解決方案。我想知道是否有更好的方法來做到這一點。映射字符串中的每個單詞以重新排序

至於字符串,每個marketLabel會略有不同,但數字(N)每次可能不同,但如果這有幫助,最大數量N可以是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這可能是下列之一:

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 

重新-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 ['%/ s%s',%match'[2],match [1]]'正確地顯示了瀏覽器,但實際的'%s'呈現在瀏覽器。 – DaveDavidson

+0

我編輯添加一個'newStr'變量集的字符串和數組元素的串聯。 – SLePort

相關問題