小能豆

How to format text in js?

javascript

There is an array consisting of a set of instructions [toggle 461,550 through 564,900] - this is the first element of the array, there are many of them.

Here, this text should be turned into this form

const instruction = "toggle";

  const start = {
    row: 461,
    col: 550,
  };

  const end = {
    row: 564,
    col: 900,
  }; 

阅读 73

收藏
2023-11-30

共1个答案

小能豆

To achieve this, you can use regular expressions to extract the relevant information from the instruction string. Here’s a JavaScript function that parses the instruction and returns the desired format:

function parseInstruction(instruction) {
  const regex = /(\w+) (\d+),(\d+) through (\d+),(\d+)/;
  const match = instruction.match(regex);

  if (!match) {
    // Handle invalid instruction format
    console.error("Invalid instruction format:", instruction);
    return null;
  }

  const [_, action, startRow, startCol, endRow, endCol] = match;

  const start = {
    row: parseInt(startRow, 10),
    col: parseInt(startCol, 10),
  };

  const end = {
    row: parseInt(endRow, 10),
    col: parseInt(endCol, 10),
  };

  return {
    action,
    start,
    end,
  };
}

// Example usage:
const instructionString = "toggle 461,550 through 564,900";
const parsedInstruction = parseInstruction(instructionString);

if (parsedInstruction) {
  console.log(parsedInstruction);
} else {
  console.log("Failed to parse instruction.");
}

This function uses a regular expression to match and capture the action (“toggle”) and the coordinates. The captured values are then converted to integers and organized into the desired format.

Note: This assumes that the instruction string is well-formed. If there’s a possibility of variations in the instruction format, you might need to adjust the regular expression or add additional validation.

2023-11-30