What's the JSLint approved way of creating a long string?

11,178

Solution 1

I think that your question can't have only one correct answer. There are many ways of writing long strings in JavaScript and it's mostly the matter of taste which one you choose. I can just describe here my point of view on the subject.

First of all you can use maxlen option of JSlint to change the default line length to any value which you like. For example

/*jslint maxlen: 130 */

But I think you know the setting already.

I suppose that you can use some Minifiers of the JavaScript code for productive usage of your JavaScripts (like Closure Compiler, Microsoft Ajax Minifier or some other). How you can easy verify on the page the code

// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==

// ADD YOUR CODE HERE
function hello(name) {
    var test = '<div>' +
                   '<h1>Foo</h1>' +
                   '<p>Lorem ipsum</p>' +
               '</div>';
    return test + name;
}
hello('New user');

will be minified to

function hello(a){return"<div><h1>Foo</h1><p>Lorem ipsum</p></div>"+a}hello("New user");

and all the string constants will be concatenated. So you can format the code with the long string constants mostly so, that the code could be better read. The minifier will do the rest of the work for you.

In the case of long URLs you can break long strings on any place which you find best from a logical point of view (I think it will always be on some '/' character). In most practical cases you have some baseURL which will be appended. So you can define the common project settings somewhere at the beginning of your file or in the separate JavaScript file

var baseLoremUrl = 'http://example.com/foo/bar/baz/fizz/buzz/lorem/';

and use it later as

'<a href="' + baseLoremUrl + 'ipsum/etc/' + '">Click me!</a>'

If you have parameters which should be appended to URL like

'http://example.com/foo/bar/baz/fizz/buzz/lorem?x=123&y=ABC'

I use always

baseLoremUrl + '?' + $.params({x: 123, y: 'ABC'})

to make the code more readable from one side and to be sure that all parameters will be correctly encoded with respect of encodeURIComponent if it's needed.

All above are the rules which I try to follow myself during writing my JavaScript code.

Solution 2

You could use something like

[
    "http://example.com",
    "foo",
    "bar",
    "baz",
    ...
    "lastSegment"
].join("/");

but this doesn't look too readable. In general, certain coding guidelines explicitly remove the limit on the length of a string for URLs (it's the same with Java's import statements - those can be arbitrarily long.)

Solution 3

First of all, I agree that there is no ‘One Solution’ for this situation and second of all I think that it’s a matter of design more than a technical issue. It’s true that sometimes it makes sense to split these kind of strings into several lines, as in the case of HTML code representations, but sometimes it doesn’t as in the example of an URL, a HASH / SHA string or even paragraphs.

So the first attempt to add the ‘/*jslint maxlen: 130 */’ option on top of your JS file will fix the problem, omitting the ‘Line Too Long’ by checking just on that file. But what about other lines on the same file, that are too long as well but should be shorter, basically a valid concern from jshint.

Since most of the cases where we want to keep the line as it is, no matter the length, are related to string representations like URLs, HASHs, SHAs and so on, using a placeholder could be a good approach. Basically the idea is to create a JS file to store them and make it available through a global variable. Then you can just call it from any script across your site, like the way jQuery is used (Just remember that you need to load placeholder file before scripts that use it). The advantage about this solution is that you need to avoid this maxlen validation only in one file (Actually we are setting the maxlen to a very high number).

my_placeholder.js

/*jslint maxlen: 500 */
//Init the placeholder
MyFeature = MyFeature || {};

//Assign URL
MyFeature.productApiURL = ‘http://this.is.the.url.to/product/API/’;

//Assign a piece of TEXT
MyFeature.productTermsOfUseText = ‘This is a very long text about something that you want to explain regarding your product terms of use for example......;

//Assign an HTML fragment
MyFeature.successfulMessageHTML = ‘<div class=”message”><div class=”header”>Successfully           created</div><div class=”detail”>some text showing the detail...</div></div>’;

//Assign a Regex to perform some validation
MyFeature.validEmailRegex = new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);

my_feature_related_file.js

//doing random awesome things

$.ajax({
  url: MyFeature.productApiURL,
  success: function() {
    $(‘#message_container’).html(MyFeature.successfulMessageHTML);
  }
});

//more awesome code here

Finally another good thing about this approach is that we are reinforcing the semantic meaning of those long strings. Anyone could understand that MyFeature.productApiURL represents the URL product API or that MyFeature.successfulMessageHTML is the HTML code for a successful message for ‘My Feature’. Basically we are explaining what it means in termS of domain (Successful Message, Product API, Valid Email...) and in which format is represented (HTML, URL, REGEX...).

source: http://moredevideas.wordpress.com/2013/09/16/line-too-long-on-jslint-and-jshint/

Share:
11,178
zzzzBov
Author by

zzzzBov

he/him Have something to say? Send me an email: zzzzBov at gmail dot com or find me on twitter @zzzzBov

Updated on July 19, 2022

Comments

  • zzzzBov
    zzzzBov almost 2 years

    As a preface, yes I'm aware that JSLint is more of a set of guidelines than rules.

    While using JSLint to clean up some code that I inherited, there are a number of places where some URLs are used in strings. They're necessary for the script, but longer than the standard 50 character line-length.

    I've been simply passing by those particular lines, as they're not an issue; however, it made me curious as to the best way to handle long string literals in JS code.

    For markup strings it makes sense to use string concatenation:

    '<div>' +
      '<h1>Foo</h1>' +
      '<p>Lorem ipsum</p>' +
    '</div>'
    

    However I don't think it makes sense for URLs:

    'http://example.com/foo/bar/baz/fizz/buzz/lorem/ipsum/etc/...'
    

    EDIT

    It also doesn't make sense for certain hash values (such as used for an API key):

    //i.e. this made up string of me bashing on my keyboard
    '0aidf9ejvr0e9vjkilkj34ioijs90eu8f9948joljse890f90jiljoi4'
    
  • zzzzBov
    zzzzBov over 10 years
    Having had over a year to reflect on this, I've taken to storing data where it actually belongs: HTML. There are certainly still times where I want good defaults in JS which may happen to exceed a certain line length, but when it comes to long strings of data, my tendency now is to pull them from [data-*] attributes, or hidden DOM elements (such as <template>).