I have a string like this:
"First player vs. Second player     Percentage%"
First player and Second player can be multiple words and before the Percentage% I'm using three  
.
How can I split this string to have an array containing First player and Second player (Percentage is not necessary)?
CodePudding user response:
Something like this should do it
const test1 = 'First player vs. Second player Percentage&emsp'
const test2 = 'Ryu vs. Ken 100&emsp'
const extractPlayers= (string) => {
const [firstPlayer, rest] = string.split(' vs. ')
const secondPlayer = rest.split(' ').filter(x => x).slice(0, -1).join(' ').trim()
return {firstPlayer, secondPlayer}
}
console.log(extractPlayers(test1))
console.log(extractPlayers(test2))
CodePudding user response:
This should do what you want:
const data=["First player vs. Second player     Percentage%",
"Another first player vs. a second one     Percentage%",
"One vs. Two    Two Percentage%"];
const res = data.map(s=>s.match(/(. ?)\s vs\.\s (. ?)\s*\ \ \ /).slice(1));
console.log(res)
In the regexp I am looking for two matching groups (. ?)
. These are non-greedy matches, as they are followed or preceded by \s
(one or more white space characters) and I don't want these whitespace characters in my matching groups.