20

I'm looking for a js library like StringUtils of commons-lang in java, which contains a lot of common methods to operating strings.

Such as:

  • IsEmpty/IsBlank - checks if a String contains text
  • Trim/Strip - removes leading and trailing whitespace
  • Equals - compares two strings null-safe
  • startsWith - check if a String starts with a prefix null-safe
  • endsWith - check if a String ends with a suffix null-safe
  • IndexOf/LastIndexOf/Contains - null-safe index-of checks
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - index-of any of a set of Strings
  • ContainsOnly/ContainsNone/ContainsAny - does String contains only/none/any of these characters
  • Substring/Left/Right/Mid - null-safe substring extractions
  • SubstringBefore/SubstringAfter/SubstringBetween - substring extraction relative to other strings
  • Split/Join - splits a String into an array of substrings and vice versa
  • Remove/Delete - removes part of a String
  • Replace/Overlay - Searches a String and replaces one String with another
  • Chomp/Chop - removes the last part of a String
  • LeftPad/RightPad/Center/Repeat - pads a String
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - changes the case of a String
  • CountMatches - counts the number of occurrences of one String in another
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable - checks the characters in a String
  • DefaultString - protects against a null input String
  • Reverse/ReverseDelimited - reverses a String
  • Abbreviate - abbreviates a string using ellipsis

It'll be better if it contains some other methods for arrays/date, etc.

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • 2
    Can you be more precise about the operations you want to perform on strings? – Redger Mar 25 '12 at 14:33
  • 2
    Please provide a link to the documentation of the `StringUtils` API. JavaScript programmers usually don't have much experience with Java, so they don't know what methods `StringUtils` provides... – Šime Vidas Mar 25 '12 at 14:44
  • Already added the link to `StringUtils` – Freewind Mar 25 '12 at 14:48
  • @Freewind From what I can see, many of the `StringUtils` static methods are available in JavaScript as instance methods. See here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String#Methods_2 – Šime Vidas Mar 25 '12 at 14:51
  • please note that some functions, like startsWith/endsWith are not supporte by IE :-( – Axel Podehl Oct 19 '18 at 10:25

4 Answers4

18

String utils - Underscore.string

Object/array utils - Underscore

Date utils - Moment.js

timrwood
  • 10,611
  • 5
  • 35
  • 42
  • 1
    Good, the underscore.string is just what I'm looking for – Freewind May 03 '12 at 01:55
  • @timrwood: any idea about the browser support ? http://stackoverflow.com/questions/25424011/underscore-string-browser-support – Adriano Aug 21 '14 at 10:35
  • Note from the authors of moment.js: "_we would like to discourage Moment from being used in new projects going forward_" ([source](https://momentjs.com/docs/#/-project-status/)). – starball Aug 11 '23 at 23:38
12

Here we go:

IsEmpty

str.length === 0

IsBlank

str.trim().length === 0

Trim

str.trim()

Equals

str1 === str2

startsWith

str.indexOf( str2 ) === 0

IndexOf

str.indexOf( str2 )

LastIndexOf

str.lastIndexOf( str2 )

Contains

str.indexOf( str2 ) !== -1

Substring

str.substring( start, end )

Left

str.slice( 0, len )

Mid

str.substr( i, len )

Right

str.slice( -len, str.length )

And so on... (should I continue?)

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • Javascript can be a nightmare when it comes to code portability: http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript/8522376#8522376 – Redger Mar 25 '12 at 15:06
  • 1
    @Redger `trim()` is the exception here. The other string methods are cross-browser. – Šime Vidas Mar 25 '12 at 15:11
  • 2
    commons-lang `org.apache.commons.lang.StringUtils` is `null` resistant here and there, for example `isEmpty` is implemented like this `return str == null || str.length() == 0;` – Jaime Hablutzel May 06 '14 at 00:30
  • 1
    although this answer is relevant as it demonstrates it's not "that hard" to compare with native JS, one might argue that if u only occasionally do JS development u might want to use a JS Util library to avoid silly mistakes & time-consuming learning. This is the goal of this library, see [the introduction statement on Undescorejs.org](underscorejs.org). This subset of underscore.js [github.com/epeli/underscore.string](underscore.string.js) is only 7Kb once minified (NOT gzipped!). The only problem I can see is the browser support being unclear, see http://stackoverflow.com/q/10657313/759452 – Adriano Aug 20 '14 at 09:59
  • correction: underscore.string is `"an extension for Underscore.js"` (it is not "a subset of underscore.js"), but you can use it as a [`"Standalone Usage"` (without underscore.js)](https://github.com/epeli/underscore.string#standalone-usage) – Adriano Aug 21 '14 at 09:58
1

I'm constantly switching between Java backend and JavaScript frontend so for me it makes a lot of sense just to blindly use the StringUtils methods and don't even think about it. It would be great if someone would take the time to port all of the Apache StringUtils methods into a JavaScript ;-)

Here's my contribution:

  String.prototype.startsWith = function(prefix) {
    return this.indexOf(prefix,0) === 0;
  };

  String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
  };

  String.prototype.substringBefore = function(str) {
    var idx = this.indexOf(str);
    if( idx!==-1 ) {
      return this.substr(0,idx);
    }
    return this;
  };

  String.prototype.substringBeforeLast = function(str) {
    var idx = this.lastIndexOf(str);
    if( idx!==-1 ) {
      return this.substr(0,idx);
    }
    return this;
  };

  String.prototype.substringAfter = function(str) {
    var idx = this.indexOf(str);
    if( idx!==-1 ) {
      return this.substr(idx+str.length);
    }
    return this;
  };

  String.prototype.substringAfterLast = function(str) {
    var idx = this.lastIndexOf(str);
    if( idx!==-1 ) {
      return this.substr(idx+str.length);
    }
    return this;
  };

  // left pad with spaces (or the specified character) to this length 
  String.prototype.leftPad = function (length,c) {
    c = c || " ";
    if( length <= this.length ) return this;
    return new Array(length-this.length+1).join(c) + this;
  };

  // right pad with spaces (or the specified character) to this length 
  String.prototype.rightPad = function (length,c) {
    c = c || " ";
    if( length <= this.length ) return this;
    return this + new Array(length-this.length+1).join(c);
  };
Axel Podehl
  • 4,034
  • 29
  • 41
  • Modifying the prototypes is generally considered bad practice in Javascript. These modifications aren't contained to your application in any way, so you will affect what code other libraries are using. – Brandon Olivier Dec 03 '18 at 20:25
  • yes, good point. But it's so convenient for m. My (non-library) code should have the freedom to do so ? To be more precise, if I would use another library in the same HTML page, you are saying that other library's startsWith() would be modified by mode code? So if that library X makes assumptions on behaviour my prototype would change that. – Axel Podehl Dec 04 '18 at 08:11
  • Any Javascript loaded on the page is going to use the same prototypes. There is no other "startsWith" because they're all using the same prototypes. You can do it if you want, but you're probably better off using something like lodash, or writing function utils, to handle some of this. – Brandon Olivier Dec 06 '18 at 16:34
1

Use both Javascript basic methods and JQuery for DOM and moment.js for dates.

Read this: Utils library if you're looking for compatibility between browsers.

Or you can write your own Apache-like commons-lang too!

Community
  • 1
  • 1
Redger
  • 573
  • 3
  • 11
  • jQuery for operations on primitive values....? – Rob W Mar 25 '12 at 14:26
  • 2
    Dates? The question is a about string operations... – Šime Vidas Mar 25 '12 at 14:45
  • He said : "It'll be better if it contains some other methods for arrays/date, etc." so basic Javascript methods for strings, JQuery for advanced handling of DOM and JSON (all strings after all) and moment.js for date parsing (strings too). – Redger Mar 25 '12 at 14:48
  • I also mentioned `date` in the last part of the question :) – Freewind Mar 25 '12 at 14:50