Five PHP Functions That Would be Great in JavaScript

Aurelio De Rosa
Share

In one of my first articles I asserted that, while the JavaScript core continues to be improved with new methods, it still misses some useful ones. Coming from a PHP background, one of the things I really appreciate is its amazing native library. This article will discusses five PHP functions that I’d love to see in JavaScript.

Please note that this article isn’t going to assert that JavaScript is worse/better than PHP. Instead, it’s an opportunity to discuss some functions and to see how they can be implemented. Also, keep in mind that these aren’t “must have” functions, but “nice to have” ones. JavaScript continues to be a great language, even if it is missing the following utilities. For all the methods described here, I’ll add them to the prototype of the proper object so that all of the instances will share the same method.

unique()

One of the most common tasks you face when dealing with arrays is the extraction of unique values. There are different ways to achieve this goal but I’m going to show a method that tries to be as general as possible. This means that the method, using the inArray() method I showed in the previously cited article, will work if the array contains primitive values or objects.

Array.prototype.unique = function (sort, sortingFunction) {
  var array = [];
  for (var i = 0; i < this.length; i++) {
    if (array.inArray(this[i]) === false)
      array.push(this[i]);
  }

  if (sort === true) {
    if (typeof sortingFunction === 'function')
      array.sort(sortingFunction);
    else
      array.sort();
  }

  return array;
};

The illustrated method has two parameters, the first is a Boolean to specify if the returned array must be sorted while the second is a reference to a sorting function. The returned array is initialised to an empty array, then for each array’s element, the function tests if it has been already added. If the element wasn’t already inside the array, it’ll be added. After pushing all the necessary elements, the method checks if the user wants to sort the array and also if a sorting function is given. If so, the array will be sorted using the given function, otherwise the sort() method will convert the items to strings and compare them in lexicographic order. Now that you know what the code does and because this is the most interesting method, I’ll show you three different examples.

Example 1 – Using Integers

In this example I’ll use a simple array containing numbers only. In the following two lines I’ll print the unique values and also the sorted unique values of the array.

var array = [1, 2, 9, 6, 2, 1, 9, 3];
console.log(array.unique()); // print [1, 2, 9, 6, 3]
console.log(array.unique(true)); // print [1, 2, 3, 6, 9]

Example 2 – Using Strings

This example uses an array of strings. This time, the second call to the unique() method, uses a sorting function that will help us return the array in reverse alphabetical order.

var array = ["hi", "hi", "hi", "aurelio", "hello", "aurelio", "de rosa", "jspro.com"];
console.log(array.unique());
// print ["hi", "aurelio", "hello", "de rosa", "jspro.com"]
console.log(array.unique(true, function(a, b){ return -1 * a.localeCompare(b); }));
// print ["jspro.com", "hi", "hello", "de rosa", "aurelio"]

Example 3 – Using Objects

The third example uses an array of objects to demonstrate how powerful unique() is.

var array = [{x: 1, y: 2}, {x: 12, y: 3}, {x: 1, y: 2}, {x: 2, y: 3}, {x: 2, y: 4}, {x: 20, y: 23}, {x: 2, y: 3}];
console.log(array.unique());
// print [{x: 1, y: 2}, {x: 12, y: 3}, {x: 2, y: 3}, {x: 2, y: 3}, {x: 20, y: 23}]

htmlSpecialChars()

In PHP you often need to print the result of an elaboration, but you have to be careful of what you’re actually injecting into your HTML code. In fact, without the proper escaping of some characters, you can allow XSS attacks. This problem can affect JavaScript code too. In PHP, to defend yourself, you can use the htmlspecialchars() function, which converts special characters like < and > into their encoded equivalent like &lt; and &gt;. This allows you to display the string without worrying about the browser interpreting it as HTML. Unfortunately, JavaScript has no equivalent native function and, for this reason, we’ll create it.

We’ll use the JavaScript native replace() method to handle this problem. What we’ll do is search for the problematic characters and replace them using the encoded equivalent entities. Since we want to change all the occurrences, we’ll use a regular expression and the g flag.

String.prototype.htmlSpecialChars = function(){
  return this
         .replace(/&/g, '&amp;')
         .replace(/</g, '&lt;')
         .replace(/>/g, '&gt;')
         .replace(/"/g, '&quot;');
};

Let’s see a demo that uses our htmlSpecialChars() method.

var string = 'Me, myself & I like to "code" <html>';
console.log(string.htmlSpecialChars());
// print Me, myself &amp; I like to &quot;code&quot; &lt;html&gt;

htmlSpecialCharsDecode()

In the previous section we saw the htmlSpecialChars() method. There are times that you want to run the inverse process, transforming the encoded string into a plain one. To achieve this goal, I’ll show you the equivalent of PHP’s htmlspecialchars_decode() function. The following is very similar to the previous so I won’t discuss it further. It simply swaps the two replace() parameters to convert from entities to the equivalent characters.

String.prototype.htmlSpecialCharsDecode = function(){
  return this
         .replace(/&amp;/g, '&')
         .replace(/&lt;/g, '<')
         .replace(/&gt;/g, '>')
         .replace(/&quot;/g, '"');
};

Let’s see a demo that uses our htmlSpecialCharsDecode() method.

var string = 'Me, myself & I like to "code" <html>';
console.log(string);
// print Me, myself & I like to "code" <html>
string = string.htmlSpecialChars();
console.log(string);
// print Me, myself &amp; I like to &quot;code&quot; &lt;html&gt;
string = string.htmlSpecialCharsDecode();
console.log(string);
// print Me, myself & I like to "code" <html>

ucwords()

The web is full of blogs that post a lot of articles each month. Many of these blogs will uppercase every word inside the posts’ titles. Imagine that you want to apply this transformation using JavaScript. Unfortunately, JavaScript has no function like PHP’s ucwords(). But, you can easily create it by yourself. The key point of the method we’re developing is to extract and then process every word inside a string. To achieve this goal we’ll rely on the JavaScript split() method and a simple regular expression. As you may guess, we’ll split the string on spaces (not just whitespaces), uppercase the words extracted and then join them again. The code for our ucwords() method is shown below.

String.prototype.ucwords = function() {
  var words = this.split(/(s+)/);
  for(var i = 0; i < words.length; i++)
    words[i] = words[i][0].toUpperCase() + words[i].substr(1, words[i].length);

  return words.join('');
};

As you can from see reading the code, inside the for loop we’ll use the toUpperCase() method to uppercase the strings’ first character, and then concatenate the remaining characters. After that, we’ll replace the old string by reassigning the new one to its position. Now that you know how the method works, let’s see an example.

var string = 'my name is aurelio de rosa';
console.log(string.ucwords());
// print My Name Is Aurelio De Rosa

ucfirst()

From the code of ucwords(), we can extract an idea for another similar PHP function – ucfirst(). The latter makes a string’s first character uppercase. What differs from the ucwords() implementation, is that we don’t need a loop to iterate over the words but we can split, convert only the first word, and then join. The source of ucfirst() is shown below.

String.prototype.ucfirst = function() {
  var words = this.split(/(s+)/);
  if (words[0] != null)
     words[0] = words[0][0].toUpperCase() + words[0].substr(1, words[0].length);

  return words.join('');
};

An example use of this function is illustrated below.

var string = 'my name is aurelio de rosa';
console.log(string.ucfirst());
// print My name is aurelio de rosa

Conclusion

Although JavaScript’s core continues to evolve with every release, there are several functions missing. However, you can find many of them in your framework of choice like jQuery. If you prefer to use raw JavaScript, or just need few functions, this article showed you how easy it is to write your own implementations. As a final note, I want to highlight that all the methods I described have been added to the prototype of their respective type – unique() to the Array prototype, and htmlSpecialChars(), htmlSpecialCharsDecode(), ucwords(), and ucfirst() to the String prototype. This allows all variables of that type to share the same code.