开发者

Normalize whitespace and other plain-text formatting routines

开发者 https://www.devze.com 2022-12-22 15:24 出处:网络
Background: The language is JavaScript. The goal is to find a library or pre-existing code to do low-level plain-text formatting.

Background:

The language is JavaScript. The goal is to find a library or pre-existing code to do low-level plain-text formatting.

I can write it myself, but why开发者_高级运维 re-invent the wheel. The issue is: it is tough to determine if a "wheel" is out there, since any search for JavaScript libraries pulls up an ocean of HTML-centric stuff. I am not interested in HTML necessarily, just text.

Example:

I need a JavaScript function that changes this:

BEFORE:

nisi ut aliquip | ex ea commodo consequat duis |aute irure dolor in
esse cillum dolore | eu fugiat nulla pariatur |excepteur sint occa
in culpa qui | officia deserunt mollit anim id |est laborum

... into this ...

AFTER:

nisi ut aliquip    | ex ea commodo consequat duis    | aute irure dolor in      
esse cillum dolore | eu fugiat nulla pariatur        | excepteur sint occa
in culpa qui       | officia deserunt mollit anim id | est laborum              

Question:

Does it exist, a JavaScript library that is non-html-web-development-centric that has functions for normalizing spaces in delimited plain text, justifying and spacing plain text?

Rationale:

Investigating JavaScript for use in a programmer's text editor.


The built-in String methods are really low-level, but you can build your own methods based on them. To make this task simpler, you can use existing string manipulation libraries like underscore.string, or at least get some inspiration there.

Here's a solution to your example problem, tested in Firefox 36 and Chrome 43:

http://jsfiddle.net/46a7bexs/7/

The basic idea is to split the entire text into an array of lines, then split them on every | character (while stripping whitespace) and store everything in a variable similar to a table (actually a 2-dimensional array).

In the next step, it iterates over all "cells" and figures out the maximum string length per column.

Finally, entries are padded to the maximum column width and joined back to gether.

I'm sure it could be done with less code and more efficient, but since no one posted a solution to that problem, I thought I share my straight-forward code.


I haven't heard on any since what you're attempting is probably no too popular.

You may have to build your own function based on JavaScript's built-in string functions.


Sure, most of the stuff out there is geared for use in browsers, but essentially anything where functions are added to the String prototype should be helpful to you. Have a look at some of the functions here:

http://code.delacap.com/p/js-methods/docs/string.html

Then you can add your own:

String.prototype.myFunc = function(){ 
    //...
};

"someStr".myfunc(); 
0

精彩评论

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