开发者

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 whitespace开发者_如何学编程s here" word</div>

So that all text inside div would be visible.


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;');


Try replacing "2" spaces with your original code:

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


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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜