javascriptstring

JavaScript Split, Split string by last DOT "."


Goal : JS function to Split a string based on dot(from last) in O(n). There may be n number of ,.(commas or dots) in string.

  1. str = '123.2345.34' expected output 123.2345 and 34

  2. Str = '123,23.34.23' expected output 123,23.34 and 23


Solution

  • In order to split a string matching only the last character like described you need to use regex "lookahead".

    This simple example works for your case:

    var array = '123.2345.34'.split(/\.(?=[^\.]+$)/);
    console.log(array);

    Example with destructuring assignment (Ecmascript 2015)

    const input = 'jquery.somePlugin.v1.6.3.js';
    const [pluginName, fileExtension] = input.split(/\.(?=[^\.]+$)/);
    console.log(pluginName, fileExtension);

    However using either slice or substring with lastIndexOf also works, and albeit less elegant it's much faster:

    var input = 'jquery.somePlugin.v1.6.3.js';
    var period = input.lastIndexOf('.');
    var pluginName = input.substring(0, period);
    var fileExtension = input.substring(period + 1);
    console.log(pluginName, fileExtension);