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.
str = '123.2345.34'expected output 123.2345 and 34Str = '123,23.34.23'expected output 123,23.34 and 23
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.
str = '123.2345.34'
expected output 123.2345 and 34
Str = '123,23.34.23'
expected output 123,23.34 and 23
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);
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
let returnFileIndex = str =>
str.split('.').pop();
Try this:
var str = '123.2345.34',
arr = str.split('.'),
output = arr.pop();
str = arr.join('.');
str and 34 in outputI'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
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);
});
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);