JavaScript Split, Split string by last DOT "." - javascript

JavaScript Split,
str = '123.2345.34' ,
expected output 123.2345 and 34
Str = 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.

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

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

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>

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

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

var test = 'filename.....png';
var lastStr = test.lastIndexOf(".");
var str = test.substring(lastStr + 1);
console.log(str);

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

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/

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

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>

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

Related

Split String after third slash

Consider the following string "/path1/path2/file.png".
Is it possible to extract "/path1/path2 through an regex? If so can you provide an example and how it works for it? If not what would be the alternative?
I would do it this way:
var str = '/path1/path2/file.png';
var regex = /(?:\/.*\/)(.*)/;
var filename = regex.exec(str)[1];
console.log(filename);
JSFiddle: https://jsfiddle.net/Ldpoqf0n/1/
this is another way without using regex:
var parts = str.split('/');
console.log(parts[parts.length - 1]);
let str = '"/path1/path2/file.png"';
console.log(str.replace(/\/\w+.\w+"/, ''));
Try this
const src = '/path1/path2/file.png'
const getFirstPart = src => (src.match(/\/.*?\/.*?(?=\/)/) || [])[0]
console.log(getFirstPart(src))
With regexes:
var path = "/path1/path2/file.png";
var patt = new RegExp("\/.*?\/[^\/]*");
var subpath = patt.exec(path)[0];
console.log(subpath)
Without regexes:
function getSubpath(path, subpathLevel) {
var arr = path.split("/");
var subpath = "";
for(var i = 0; i < subpathLevel && i < arr.length; i++)
subpath += "/" + arr[i+1];
return subpath;
}
console.log(getSubpath("/path1/path2/file.png", 2));
In subpathLevel variable you can set the quantity of slashes you want to consider (in the example is 2).

How to split two dimensional array in JavaScript?

I have string like below:
"test[2][1]"
"test[2][2]"
etc
Now, I want to split this string to like this:
split[0] = "test"
split[1] = 2
split[2] = 1
split[0] = "test"
split[1] = 2
split[2] = 2
I tried split in javascript but no success.How can it be possible?
CODE:
string.split('][');
Thanks.
Try this:
.replace(/]/g, '') gets rid of the right square bracket.
.split('[') splits the remaining "test[2[1" into its components.
var str1 = "test[2][1]";
var str2 = "test[2][2]";
var split = str1.replace(/]/g, '').split('[');
var split2 = str2.replace(/]/g, '').split('[');
alert(split);
alert(split2);
you can try :
string.split(/\]?\[|\]\[?/)
function splitter (string) {
var arr = string.split('['),
result = [];
arr.forEach(function (item) {
item = item.replace(/]$/, '');
result.push(item);
})
return result;
}
console.log(splitter("test[2][1]"));
As long as this format is used you can do
var text = "test[1][2]";
var split = text.match(/\w+/g);
But you will run into problems if the three parts contain something else than letters and numbers.
You can split with the [ character and then remove last character from all the elements except the first.
var str = "test[2][2]";
var res = str.split("[");
for(var i=1, len=res.length; i < len; i++) res[i]=res[i].slice(0,-1);
alert(res);

How to split a number after n digits in javascript?

I have a number 2802 which is stored as a string in the backend. I want to split this number into 2 parts as 28 and 02 which should be shown as date 28/02? How can I do it with '/' in between them?
Try this : you can use substring as shown below. substring used for getting string between start index and end index. In your case, get string from 0 to 1 and then 2 to 3.
var str = "2802";
str = str.substring(0,2) + "/" + str.substring(2,4);
alert(str);
More information on Substring
Solution with regex
var res = "2802".match(/\d{2}/g).join('/');
document.write(res);
Are you asking about simple string manipulation?
var str = "1234";
var res = str.substr(0, 2)+"/"+str.substr(2,4);
You can do this:
var str = "2802";
str = str.split('').map(function(el, i){
if(i == 2){ el = '/'+el}
return el;
});
document.querySelector('pre').innerHTML = str.join('');
<pre></pre>
With regular expression:
var str = "2802";
str = str.replace(/(.{1,2}$)/gi, '/$1');
document.querySelector('pre').innerHTML = str;
<pre></pre>
var str = "2802";
var output = [str.slice(0, 2), str.slice(2)].join('/');
In this context conside 2802, 28 is date and 02 is month
Here 112, 028 what is date and month ?
A more generic solution could be
var num = 2802;
var output = String(num).match(new RegExp('.{1,2}', 'g')).join("/");
replace 2 with which ever number to split the number after n digits.
var n = 2;
var output = String(num).match(new RegExp('.{1,'+n+'}', 'g'));
var db_date = '112';
var date_str = '';
if(db_date.slice(0,1)==0){
var date_val = db_date.slice(0,2);
var month_val = db_date.slice(2,3);
if(month_val<=9){
month_val = '0'+month_val;
}
}else{
var date_val = db_date.slice(0,1);
date_val = parseInt(date_val);
if(date_val<=9){
date_val = date_val.toString();
date_val = '0'+date_val;
}
var month_val = db_date.slice(1,3);
}
alert(date_val+'/'+month_val);

Extracting end of String - Javascript

Say I have a string 12.13.14
How can I get the characters after the last dot. (in this case 14)?
There can be more than 2 characters.
Examples would be 34.45.657
10.11.46256
So after the last dot could be any amount of characters.
I've messed around with .slice() but can't get anywhere.
You have a bunch of options. One is split and pop:
var str = "12.13.14";
var last = str.split('.').pop();
document.body.innerHTML = last;
Another is a regular expression
var str = "12.13.14";
var match = /\.([^.]+)$/.exec(str);
var last = match && match[1];
document.body.innerHTML = last;
Or a rex and replace:
var str = "12.13.14";
var last = str.replace(/^.*\.([^.]+)$/, "$1");
document.body.innerHTML = last;
Or lastIndexOf and substring, as Ananth shows.
var str = '34.45.657';
console.log(str.substring(str.lastIndexOf('.') + 1));
You can do that in multiple ways:
First way:
var myString = '12.13.14';
var lastItem = myString.split('.').pop();
console.log(lastItem);
Second Way:
var myString = '12.13.14';
var lastItem = myString.slice(myString.lastIndexOf('.')+1);
console.log(lastItem);
Third Way:
var myString = '12.13.14';
var lastItem = myString.substring(myString.lastIndexOf('.') + 1);
console.log(lastItem);
and so on ,...
An easy solution would be to use split() which takes a delimiter.
You could split your string on dots and since split returns an array you could use pop() to get the last result.
e.g.
'34.345.3456'.split('.').pop(); // 3456
Easy solution to get your answer like this
var txt= document.getElementById("Text1").value;
var s1 = txt.lastIndexOf(".");
txt = txt.substring(0, s1);

How to get substring value from main string?

I have string similar to this one.
HTML
var str = "samplestring=:customerid and samplestring1=:dept";
JS
var parts = str.split(':');
var answer = parts;
I want to trim substrings which starts with colon: symbol from the main string
But it is returing the value like this
samplestring=,customerid and samplestring1=,dept
But I want it something like this.
customerid,dept
I am getting main string dynamically it may have colon more then 2.
I have created a fiddle also link
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.match(/:(\w+)/g).map(function(s){return s.substr(1)}).join(","))
you can try regex:
var matches = str.match(/=:(\w+)/g);
var answer = [];
if(matches){
matches.forEach(function(s){
answer.push(s.substr(2));
});
}
Here's a one-liner:
$.map(str.match(/:(\w+)/g), function(e, v) { return e.substr(1); }).join(",")
Try
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(':');
var dept = parts[2];
var cus_id = parts[1].split(' and ')[0];
alert(cus_id + ", " + dept );
Using this you will get o/p like :customerid,dept
this will give you what you need...
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(' and ');
var answer = [];
for (var i = 0; i < parts.length; i++) {
answer.push(parts[i].substring(parts[i].indexOf(':')+1));
}
alert(answer);
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.replace(/[^:]*:(\w+)/g, ",$1").substr(1))
You can try it like this
var str = "samplestring=:customerid and samplestring1=:dept and samplestring11=:dept";
var results = [];
var parts = str.split(' and ');
$.each(parts, function( key, value ) {
results.push(value.split(':')[1]);
});
Now the results array contains the three values customerid, dept, and dept
Here \S where S is capital is to get not space characters so it will get the word till first space match it, so it will match the word after : till the first space and we use /g to not only match the fisrt word and continue search in the string for other matches:
str.match(/:(\S*)/g).map(function(s){return s.substr(1)}).join(",")

Categories

Resources