18

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

2
  • 1
    on what basis you are splitting... any logic ? Commented Apr 23, 2015 at 13:49
  • dot(.)(last occurrence) Commented Apr 23, 2015 at 13:51

14 Answers 14

44

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Life saver! My old solution was only with split, but that won't take into account various '.' in the file name.
16

var str = "filename.to.split.pdf"
var arr = str.split(".");      // Split the string using dot as separator
var lastVal = arr.pop();       // Get last element
var firstVal = arr.join(".");  // Re-join the remaining substrings, using dot as separator

console.log(firstVal + " and " + lastVal);  //Printing result

Comments

11

I will try something like bellow

var splitByLastDot = function(text) {
    var index = text.lastIndexOf('.');
    return [text.slice(0, index), text.slice(index + 1)]
}

console.log(splitByLastDot('123.2345.34'))
console.log(splitByLastDot('123,23.34.23'))

Comments

5

I came up with this:

var str = '123,23.34.23';
var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
document.getElementById('output').innerHTML = JSON.stringify(result);
<div id="output"></div>

Comments

5
let returnFileIndex = str =>
    str.split('.').pop();

1 Comment

Could you please add an explanation for your answer? :)
1

Try this:

var str = '123.2345.34',
    arr = str.split('.'),
    output = arr.pop();
str = arr.join('.');

2 Comments

this will give "123.2345"
123.2345 in str and 34 in output
1
var test = 'filename.....png';
var lastStr = test.lastIndexOf(".");
var str = test.substring(lastStr + 1);
console.log(str);

Comments

1

I'm typically using this code and this works fine for me.

Jquery:

var afterDot = value.substr(value.lastIndexOf('_') + 1);
console.log(afterDot);

Javascript:

var myString = 'asd/f/df/xc/asd/test.jpg'
var parts    = myString.split('/');
var answer   = parts[parts.length - 1];
console.log(answer);

Note: Replace quoted string to your own need

1 Comment

You realise that there isn’t any jQuery here, don’t you?
0

My own version:

var mySplit;
var str1;
var str2;
$(function(){
  mySplit = function(myString){
    var lastPoint = myString.lastIndexOf(".");
    str1 = myString.substring(0, lastPoint);
    str2 = myString.substring(lastPoint + 1);
  }
  mySplit('123,23.34.23');
  console.log(str1);
  console.log(str2);
});

Working fiddle: https://jsfiddle.net/robertrozas/no01uya0/

Comments

0
Str = '123,23.34.23';

var a = Str.substring(0, Str.lastIndexOf(".")) //123,23.34 
var b = Str.substring(Str.lastIndexOf(".")) //23

Comments

0

Try this solution. Simple Spilt logic

 <script type="text/javascript">

 var str = "123,23.34.23";
 var str_array = str.split(".");
 for (var i=0;i<str_array.length;i++)
 {
     if (i == (str_array.length-1))
     {
         alert(str_array[i]);
     }
 }
 </script>

Comments

0

very very old question, but I believe it always worth another answer ;-)

const s = '123.2345.123456.34';

function splitString(t) {
  let a = t.split(/\./);
  return [a.slice(0, -1).join('.'), a.pop()];
}

const [first, last] = splitString(s);

console.log(`first: ${first}, last: ${last}`);

Comments

0

By using the new flat() method with join() and pop() you can do:

Example 1

// expected output 123.2345 and 34
var str = '123.2345.34';
var result = str.split('.');
var last = result.pop();
var rest = result.flat().join('.');
console.log(rest, last);

Example 2

// expected output 123,23.34 and 23
var str = '123,23.34.23';
var result = str.split('.');
var last = result.pop();
var rest = result.flat().join('.');
console.log(rest, last);

Comments

-1

The simplest way is mentioned below, you will get pdf as the output:

var str = "http://somedomain.com/dir/sd/test.pdf"; var ext = str.split('.')[str.split('.').length-1];

Output: pdf

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.