DaveDavidson DaveDavidson - 23 days ago 8
React JSX Question

map each word in string to reorder

Currently I am trying to re-order my strings slightly. I believe I need to do this my using

.map
so, I need to re-order the strings Set N Total Games Over/Under N. N representing a random number. This is stored in the var of
market
. This would need reordering to Under/Over N Total Games Set N. I have started to do this by using a lot of messy if statements, and using
substr
but this is not a great solution as my code looks really messy, and is not a great solution anyway. I wondered if there was any better way of doing this.

As for the string , each marketLabel will be slightly different only that the number (N) could be different each time, but the maximum number N can be is 5 if this helps.

At the minute code wise this is what I have:

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


So in summary, what I need is the marketLabel which could be one of the following:

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


to be re-ordered into:

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

Answer

Uging regular expressions:

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

Numbers, Over and Under strings are captured and reordered by printing the match array elements.

A schema is better than words:

enter image description here

You can also just capture numbers and inject them in string in correct order:

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