映射字符串中的每个单词以重新排序

时间:2016-11-17 09:52:35

标签: javascript reactjs

目前我正在尝试稍微重新排序我的字符串。我相信我需要使用.map这样做,所以我需要重新排序字符串Set N Total Games Over / Under N. N代表一个随机数。它存储在market的变量中。这需要重新排序到Under / Over N Total Games Set 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

重新订购:

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 个答案:

答案 0 :(得分:1)

使用正则表达式:

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);

通过打印Over数组元素来捕获并重新排序数字,Undermatch字符串。

架构优于单词:

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);