user4823536
user4823536

Reputation: 7

Fastest way to flip multiline text in jquery

I'm looking for the shortest line of unobfuscated code to reverse multiline strings in jquery. For example,

abcd

edfg

hijk

should become

dcba

gfde

kjih

An extremely complicated example would look like:

function fliptext() {
    var text = document.getElementById('input_output').value;
    text = text.replace(/\r/gi, '');
    text = text.replace(/([^a-z 0-9\n])/gi, ' $1 ');
    text = text.split('\n').reverse().join('\n');
    text = text.split('').reverse().join('');
    text = text.replace(/ ([^a-z 0-9\n]) /gi, '$1');
    document.getElementById('input_output').value = text;
}

What's a better way?

Upvotes: 1

Views: 106

Answers (4)

keune
keune

Reputation: 5795

You could do;

text = text.split('\n').map(function(el) {return el.split('').reverse().join('')}).join('\n');

First, we split the text by newlines and get an array of lines, then reverse every line, then join the array with a newline ('\n') and get a string.

Upvotes: 4

phoenix.mstu
phoenix.mstu

Reputation: 164

Here is the shortest one:

var text = "abcdef\n123\n789";
text = text.split('').reverse().join('').split("\n").reverse().join("\n");

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47117

var el = document.getElementById('input_output');
var value = el.value;
// Split on newline and iterate over each line 
//   this will preserve the the line numbers.
var output = value.split('\n').map(function(line) {
  // Split on each character this will create an array
  //   like this: "abc" -> ["a", "b", "c"]
  //   .reverse() will reverse the array -> ["c", "b", "a"]
  //   .join will make the array a string again.
  return line.split('').reverse().join('');
}).join('\n');

Upvotes: 0

user4823536
user4823536

Reputation: 7

CSS:

.flipped {
    transform: scale(-1, 1);
}

jQuery:

$("#some_div").addClass("flipped");

Upvotes: -2

Related Questions