Rune Grønkjærs Blog
Abonnér på mit feed

Javascript String extension

This time the subject will be extension of strings in javascript. Real programming languages usually contains quite a lot of methods you can call on it’s strings. In javascript you have to do much of the work yourself. I have over time collected or written some extensions to the string object that can make life a lot easier. For a complete reference of all the string object’s methods, follow this link to w3schools.

All results are calculated with the correct method and not just a hardcoded entry.

.trim(), .trimEnd(), trimStart()

Trim methods used to remove unwanted spaces from the start and / or end of the javascript string. All three methods use the built in replace method along with regular expressions.
//Trim removes spaces both before and after the string
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); };
//trimEnd removes spaces at the end of the string
String.prototype.trimEnd = function() { return this.replace(/\s+$/, ''); };
//trimStart removes spaces at the beginning of the string
String.prototype.trimStart = function() { return this.replace(/^\s+/, ''); };

//trim example
var trimString = "  This string has some not very usefull spaces at the ends   ",
    trimTest = jQuery("#TrimTest");
trimTest.html("'" + trimString + "'");
trimTest.html(trimTest.html() + "<br />'" + trimString.trim() + "'");
trimTest.html(trimTest.html() + "<br />'" + trimString.trimEnd() + "'");
trimTest.html(trimTest.html() + "<br />'" + trimString.trimStart() + "'");

The result is such:

.format()

With the format method you can replace the tokens in the text with arguments from the method’s parameters.
Real format methods are much more than that and maybe I will implement support for more functionality when I need it.
//An additional format method to the String object
//Can be used with parameters
String.format = function(text) {
  //Check if there is more than one argument as parameters
  if (arguments.length <= 1) {
    //If only one parameter, we can return when as there is nothing to format
    return text;
  }
  //We are ready to run the arguments
  var tokenCount = arguments.length - 2;
  for (var token = 0; token <= tokenCount; token++) {
    //We iterate through the text tokens and replace their spot with arguments
    text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
  }
  return text;
};

//format example
var formatString = "Hi {0}, are you having a nice day? Greeting from {1}";
jQuery("#FormatTest").html("'Before formating: '" + formatString + "'<br />After formating: '" + String.format(formatString, "Visitor", "Rune") + "'");
The result is such:

.reverse()

The reverse method mirrors a string.
//Mirrors the string.
String.prototype.reverse = function() { 
  return this.split('').reverse().join('');
};

//reverse example
var reverseString = "evian mmh";
jQuery("#ReverseTest").html("Before reverse: " + reverseString + "<br />After reverse: " + reverseString.reverse());

The result is such:

.contains()

Instead of having to use the built indexOf() method, and have a number returned, you can instead use contains which return a bool.
The contains method, as default, is case insensitive, which is very nice. I have given the user a parameter to chose case sensitive if needed.
//Returns true if the text is contained in the string
String.prototype.contains = function(text, isCaseSensitive) {
  return !!(new RegExp(text, !isCaseSensitive ? "i" : "" + "g").test(this));
};

//contains example
var containsString = "The quick brown Rune jumps over the lazy dog";
jQuery("#ContainsTest").html(containsString.contains("Brown") + "<br />" + containsString.contains("Brown", true));
The result is such:

.endsWidth()

Endswith doing basically the same as contains. It only searches the end of the string.
//Returns true if the text is at the end of the string
String.prototype.endsWidth = function(text, isCaseSensitive) {
  return !!(new RegExp(text + "$", !isCaseSensitive ? "i" : "" + "g").test(this));
};

//endsWidth example
var endsWidthString = "The quick brown Rune jumps over the lazy dog";
jQuery("#EndsWidthTest").html(endsWidthString.endsWidth("Dog") + "<br />" + endsWidthString.endsWidth("Dog", true));
The result is such:

.startsWidth()

The startsWidth method is basically doing the same as contains. It only searches the beginning of the string.
//Returns true if the text is in the beginning of the string
String.prototype.startsWidth = function(text, isCaseSensitive) {
  return !!(new RegExp("^" + text, !isCaseSensitive ? "i" : "" + "g").test(this));
};

//startsWidth example
var startsWidthString = "The quick brown Rune jumps over the lazy dog"
jQuery("#StartsWidthTest").html(startsWidthString.startsWidth("den") + "<br />" + startsWidthString.startsWidth("den", true));
The result is such:

.toArray()

A very small and simple method which makes it somewhat easier to make a string to an array of characters
//Returns the string as an array
String.prototype.toArray = function() {
  return this.split('');
}

//toArray example
var toArrayString = "The quick brown Rune jumps over the lazy dog";
jQuery("#ToArrayTest").html(toArrayString + "<br />" + toArrayString.toArray());
The result is such:

.toIntArray()

The toIntArray method creates an array with each characters unicode number. In the example I make a simple calculation to show that we only gets integers.
//returns the string as an array with each unicode characters integer
String.prototype.toIntArray = function() {
  var returnArray = [];
  for (var i = 0; i < this.length; i++) {
    returnArray.push(this.charCodeAt(i));
  }
  return returnArray;
};

//toIntArray example
var toIntArrayString = "The quick brown Rune jumps over the lazy dog",
    intArray = toIntArrayString.toIntArray();
jQuery("#ToIntArrayTest").html(toIntArrayString + "<br />" + intArray + "<br />intArray[2] * intArray[7] = " + (intArray[2] * intArray[7]));
The result is such:

.remove()

The remove method works by removing a portion of the string. It removes from the starting index and "length" characters forward.
//Removing a piece of the string start and "length" forward
String.prototype.remove = function(start, length) {
  var s = '';
  if (start > 0)
    s = this.substring(0, start);

  if (start + length < this.length)
    s += this.substring(start + length, this.length);
  return s;
};

//remove example
var removeString = "The quick brown Rune jumps over the lazy dog";
jQuery("#RemoveTest").html(removeString + "<br />" + removeString.remove(11, 6));
The result is such:

.htmlEntities()

This method html encodes the html of the text. This means that the html will not be interpreted as html by the browser.
//html encoding the text
String.prototype.htmlEntities = function() {
  return this.replace(/&/g, '&').replace(//g, '>');
};

//htmlEntitiesString example
var htmlEntitiesString = "<div>The quick brown <strong>Rune</strong> jumps over the lazy dog</div>";
jQuery("#HtmlEntitiesTest").html(htmlEntitiesString + "<br />" + htmlEntitiesString.htmlEntities());
The result is such:

.stripTags()

This method removes all html tags in the text. In the example i use the htmlentities method to show that all html tags are removed.
//returnerer en string uden HTML tags
String.prototype.stripTags = function() {
  return this.replace(/<\/?[^>]+>/gi, '');
};

//stripTags ekesmpel
var stripTagsString = "<div>The quick brown <strong>Rune</strong> jumps over the lazy dog</div>";
jQuery("#StripTagsTest").html(stripTagsString.htmlEntities() + "<br />" + stripTagsString.stripTags().htmlEntities());
The result is such:
This post was written in Extension, Javascript, regexp, String. Ad permalink to favorites. Follow all comments with RSS feed for this posts. Drop a comment or a trackback: Trackback URL. | Læs denne side på dansk dansk version

Drop a comment

Your email is never published nor shared. Required fields are marked *

*
*

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Dansk version