Home > Net >  Is there any shortcut to change 1 word per line to any #words per line?
Is there any shortcut to change 1 word per line to any #words per line?

Time:12-16

For example:

one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve

to

one two three
four five six
seven eight nine
ten eleven twelve

I couldn't figure out how to do this and was only able to do vice versa on vscode.

CodePudding user response:

Not a shortcut, but you can easily do such job with find ans replace.

  • Ctrl H
  • Find what: (\w )\R(\w )\R(\w )
  • Replace with: $1 $2 $3
  • CHECK Wrap around
  • CHECK Regular expression
  • Replace all

Explanation:

(\w )           # group 1, 1 or more word characters
\R              # any kind of linebreak
(\w )           # group 2, 1 or more word characters
\R
\R              # any kind of linebreak

Screenshot (before):

enter image description here

Screenshot (after):

enter image description here

CodePudding user response:

Not VS Code, but you can do that using this snippet:

Just bookmark this answer if you need it again (or copy and paste the snippet info into an HTML file on your device). Also, I think the "Copy to clipboard" button doesn't work because the snippet runs in a cross-origin iframe, but it should work in a same-origin context.

function splitWordsPerLine (text, wpl = 1) {
  let result = '';
  wpl = wpl < 1 ? 1 : wpl;
  let count = wpl;

  for (const word of text.split(/\s /)) {
    count -= 1;
    let line = word;
    if (count === 0) {
      line  = '\n';
      count = wpl;
    }
    else line  = ' ';
    result  = line;
  }

  return result.trim();
}

function getWPL (numberInput) {
  if (!numberInput) return 1;
  const wpl = parseInt(numberInput.value, 10);
  return Number.isNaN(wpl) ? 1 : wpl;
}

function handleInput (event) {
  const wpl = getWPL(event.target);
  const textInput = document.getElementById('text');
  if (!textInput) return;
  textInput.value = splitWordsPerLine(textInput.value, wpl);
}

async function handleClick (event) {
  let message = 'Copying failed            
  • Related