Extracting end of String - Javascript - 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);

Related

how do i split this string into two starting from a specific position

I have this string:
var str=' "123","bankole","wale","","","","xxx" ';
I need to split this string into two. The split should start from the last comma. Resulting in:
' "123", "bankole","wale","","","" ' and ' "xxx" '
I used the below to get the "xxx":
str.split(/[,]+/).pop(); \\""
however note that the last "" can also be "something"
There are many ways to achive this.
You could split your string on commas with split(), then get the last element of the created array with slice(). Then join() the elements left in the first part back into a string.
var str = '"123", "bankole","wale","","","" and ""';
var arr = str.split(',')
var start = arr.slice(0, -1).join(',')
var end = arr[arr.length-1];
console.log(start);
console.log(end);
In the above code, the part that extracts the last part after the last comma is arr.slice(0, -1). -1 means start looking from the end of the array and go back 1.
So if you need to split from the second last, use arr.slice(0, -2)
var str = '"123", "bankole","wale","","","" and ""';
var arr = str.split(',')
var start = arr.slice(0, -2).join(',')
var end = arr.slice(-2).join(',')
console.log(start);
console.log(end);
You can simply use String.prototpye.lastIndexOf() and String.prototpye.substring()
var str='"123","bankole","wale","","","","something"';
var lastCommaIndex = str.lastIndexOf(',');
var part1 = str.substring(0, lastCommaIndex);
var part2 = str.substring(lastCommaIndex + 1, str.length);
console.log(part1)
console.log(part2)
It sounds like your regex is already what you're looking for, and that you're simply looking to extract the final segment. This can be done with array_name[array_name.length - 1], as can be seen in the following:
var str = ' "123","bankole","wale","","","","something" ';
var parts = str.split(/[,]+/);
console.log(parts[parts.length - 1]);
If you also want to remove the quotes, you can run .replace(/['"]+/g, '') on the extracted string, as is seen in the following:
var str = ' "123","bankole","wale","","","","something" ';
var parts = str.split(/[,]+/);
var extracted = parts[parts.length - 1];
console.log(extracted.replace(/['"]+/g, ''));
Hope this helps! :)
If you want to use regex you can use negative lookahead as follows.
var str = ' "123","bankole","wale","","","","something" ';
var splitResult = str.split(/,(?!.*,)/);
console.log(splitResult[0])
console.log(splitResult[1])

JavaScript replace string and comma if comma exists else only the string

I got a string like:
var string = "string1,string2,string3,string4";
I got to replace a given value from the string. So the string for example becomes like this:
var replaced = "string1,string3,string4"; // `string2,` is replaced from the string
Ive tried to do it like this:
var valueToReplace = "string2";
var replace = string.replace(',' + string2 + ',', '');
But then the output is:
string1string3,string4
Or if i have to replace string4 then the replace function doesn't replace anything, because the comma doens't exist.
How can i replace the value and the commas if the comma(s) exists?
If the comma doesn't exists, then only replace the string.
Modern browsers
var result = string.split(',').filter( s => s !== 'string2').join(',');
For older browsers
var result = string.split(',').filter( function(s){ return s !== 'string2'}).join(',');
First you split string into array such as ['string1', 'string2', 'string3', 'string4' ]
Then you filter out unwanted item with filter. So you are left with ['string1', 'string3', 'string4' ]
join(',') convertes your array into string using , separator.
Split the string by comma.
You get all Strings as an array and remove the item you want.
Join back them by comma.
var string = "string1,string2,string3,string4";
var valueToReplace = "string2";
var parts = string.split(",");
parts.splice(parts.indexOf(valueToReplace), 1);
var result = parts.join(",");
console.log(result);
You only need to replace one of the two commas not both, so :
var replace = string.replace(string2 + ',', '');
Or :
var replace = string.replace(',' + string2, '');
You can check for the comma by :
if (string.indexOf(',' + string2)>-1) {
var replace = string.replace(',' + string2, '');
else if (string.indexOf(string2 + ',', '')>-1) {
var replace = string.replace(string2 + ',', '');
} else { var replace = string.replace(string2,''); }
You should replace only 1 comma and also pass the correct variable to replace method such as
var string = "string1,string2,string3,string4";
var valueToReplace = "string2";
var replaced = string.replace(valueToReplace + ',', '');
alert(replaced);
You can replace the string and check after that for the comma
var replace = string.replace(string2, '');
if(replace[replace.length - 1] === ',')
{
replace = replace.slice(0, -1);
}
You can use string function replace();
eg:
var string = "string1,string2,string3,string4";
var valueToReplace = ",string2";
var replaced = string.replace(valueToReplace,'');
or if you wish to divide it in substring you can use substr() function;
var string = "string1,string2,string3,string4";
firstComma = string.indexOf(',')
var replaced = string.substr(0,string.indexOf(','));
secondComma = string.indexOf(',', firstComma + 1)
replaced += string.substr(secondComma , string.length);
you can adjust length as per your choice of comma by adding or subtracting 1.
str = "string1,string2,string3"
tmp = []
match = "string3"
str.split(',').forEach(e=>{
if(e != match)
tmp.push(e)
})
console.log(tmp.join(','))
okay i got you. here you go.
Your question is - How can i replace the value and the commas if the comma(s) exists?
So I'm assuming that string contains spaces also.
So question is - how can we detect the comma existence in string?
Simple, use below Javascript condition -
var string = "string1 string2, string3, string4";
var stringToReplace = "string2";
var result;
if (string.search(stringToReplace + "[\,]") === -1) {
result = string.replace(stringToReplace,'');
} else {
result = string.replace(stringToReplace + ',','');
}
document.getElementById("result").innerHTML = result;
<p id="result"></p>

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 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(",")

JavaScript Split, Split string by last DOT "."

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

Categories

Resources