Home > database >  Javascript handling specific text format
Javascript handling specific text format

Time:04-21

Hello i need help with handling specific text format.

It should look like this

Input: !tip 10 coin

Output: !tip number string

I need to split this text to 3 section, first its immutable string its always !tip and then number and string. I need to get any number. And string any string. Anyone could help me with this. I tried lot of things but nothing helped me. Thanks

CodePudding user response:

You'll probably want to use a regular expression, but you can also iterate the characters.

Below is an example for the specific case in your question. However, if you're going to be parsing other commands, you'll probably want to first parse the command, then parse the arguments in a modular way. Good luck!

function parseTip (input) {
  const groups = input.match(/^(?<command>!tip)\s (?<amount>(?:\d .)?\d )\s (?<type>. )\s*$/iu)?.groups;
  if (!groups) {
    // you can throw an error here instead or handle invalid input however you'd like
    return undefined;
  }

  const {command, amount, type} = groups;
  return {
    command,
    amount: Number(amount),
    type,
  };
}

const inputs = [
  '!tip 10 coin',
  '!tip 3.5 coin',
  '!tip 400 giraffes',
  '!TIP 5 ideas',
  '!t 10 coin', // invalid
  '!tip two coin', // invalid
];

for (const input of inputs) {
  console.log(input, parseTip(input));
}

  • Related