Somebody
Somebody

Reputation: 9645

Javascript - How to save exact whitespace count between words from textarea

How to save exact whitespace count between words from textarea when putting it's value into html?

<textarea>word "10 whitespaces here" word "20 whitespaces here" word</textarea>

html:

<div style="width:50px;overflow:hidden;">word "10 whitespaces here" word "20 whitespaces here" word</div>

So that all text inside div would be visible.

Upvotes: 2

Views: 1670

Answers (3)

Ewan Heming
Ewan Heming

Reputation: 4648

Try replacing "2" spaces with your original code:

$('div').html($('textarea').text().replace("  ", " &nbsp;", "g"));

Upvotes: 2

jAndy
jAndy

Reputation: 236032

Well, if you just want to avoid line-breaks, CSS is your best friend here:

body {
    white-space: nowrap;
}

Of course it's probably not a great idea to set that property to the document.body, but you could display the value in some div node and give that element the nowrap.

Do it like this:

var foo = "<textarea>aefawefawef      dqwfawe        fawef awef awefawef awef awef awe fawe</textarea>";


var sp = foo.split(/\s/).filter(function(elem) {
    return !!elem;
}).join('nbsp;');

console.log(sp);

This will .split() the string after each whitespace and filter all empty results. After that is done, it joins the new array with nbsp;. That way, you get rid of the multiple whitespace characters (plus, this should be faster than any regexp solution can be).


jQuery(document.body).append(jQuery('<textarea>aefawefawef      dqwfawe        fawef awef awefawef awef awef awe fawe</textarea>').val().split(/\s/).filter(function(elem) { return !!elem; }).join('nbsp;');

Upvotes: 2

Nathan Feger
Nathan Feger

Reputation: 19506

Can you separate out the ''? This does not necessarily fix your problem, but that textarea is really a constant that shouldn't be subject to the whims of replace.

var text = 'aefawefawef      dqwfawe        fawef awef awefawef awef awef awe fawe'.replace(' ','&nbsp;');
jQuery('body').append(jQuery('<textarea>'+text+'</textarea>').val());

Upvotes: 0

Related Questions