Cut text using jquery - javascript

How to cut text using jQuery? For example :
if output like :
new/2016/songs1.mp3
new/2015/songsx.mp3
new/songs3.mp3
Need output :
songs1.mp3
songsx.mp3
songs3.mp3
I want to put only file name with extension like songs-name.mp3 not directory, so i want to cut this using jQuery.

split it and take the last item
var str = "new/2016/songs1.mp3";
var items = str.split( "/" );
alert(items[items.length - 1 ]);
or simply
alert( str.split("/").pop() );
if you want to remove the rest of the text then
var str = "new/2016/songs1.mp3";
var items = str.split( "/" );
str = items[items.length - 1 ];
or
str = str.split("/").pop();

Check it out:
Here i use split function to split the string and then its return an array.
From that array we have to get the last portion i.e, Song name, So we have to get the length of that array.
After that we alert the array with the index of last portion.
var str = "new/2016/songs1.mp3";
var arr = str.split("/");
alert(arr[(arr.length) - 1]);

try this
var filepath = "new/2015/songsx.mp3";
console.log(filepath.slice(filepath.lastIndexOf("/")+1));
Using the slice method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) you can get a part of a string.
Using the lastIndexOf method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) returns the index of the last occurrence of the given string (or -1 if given string does not occur in the string).
So what we are doing is getting the slice if the file path starting with the first character after the las "/" in the filepath variable.

Related

Javascript extract string from start to 0/, removing anything after 0/

I have a string which looks like this:
file:///storage/emulated/0/Pictures/IMG212.jpg
I want to remove anything from Pictures onwards so I would get this:
file:///storage/emulated/0/
How can I do this?
var regex = /^.*0\//
var matches = str.match(regex);
console.log(matches[0]);
You could find the index of /0 and use substring to select everything up to that point, like so:
const line = "file:///storage/emulated/0/Pictures/IMG212.jpg";
// Get the location of "/0", will be 24 in this example
const endIndex = line.indexOf("/0");
// Select everything from the start to the endIndex + 2
const result = line.substring(0, endIndex+2);
The reason why we add +2 to the endIndex is because the string that we're trying to find is 2 characters long:
file:///storage/emulated/0/Pictures/IMG212.jpg
[24]--^^--[25]
You can split the string using split method:
const myString = "file:///storage/emulated/0/Pictures/IMG212.jpg";
const result = myString.split("0/")[0] + "0/";
console.log(result); // file:///storage/emulated/0/
documentation for split method on MDN

How to get a sub-string after the last specified char ? Javascript

lets say I have the following string :
var text = "A_B_C_190"
I want to be able to extract the number at the end (the last 3 chars after the last _ )
I tired :
text.substr(text.indexOf('_'), -1)
but that gave me null
You can use string.prototype.split and array.prototype.pop:
var text = "A_B_C_190";
console.log(text.split('_').pop());
You have to use lastIndexOf method.
var text = "A_B_C_190"
ans = text.substr(text.lastIndexOf('_')+1)
console.log(ans)
If you want to convert it to an integer, use parseInt(ans)

Split text with a single code

var objname = "Image1-123456-789.png"
quick question i wanted to split this text without match them together again.
here is my code
var typename = objname.split("-");
//so it will be Image1,123456,789.png
var SplitNumber = typename[1]+'-'+typename[2];
var fullNumber = SplitCode.split('.')[0];
to get what i wanted
my intention is to get number is there anyway i can split them without join them and split again ?
can a single code do that perfectly ? my code look like so many job.
i need to get the 123456-789.
The String.prototype.substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between "start" and "end", not including "end" itself.
var objname = "Image1-123456-789.png";
var newname = objname.substring(objname.indexOf("-")+1, objname.indexOf("."));
alert(newname);
An alternate can be using Join. You can use slice to fetch range of values in array and then join them using -.
var objname = "Image1-123456-789.png";
var fullnumber = objname.split("-").slice(1).join("-").split(".")[0];
alert(fullnumber)
Reference
Join Array from startIndex to endIndex
Here is your solution
var objname = "Image1-123456-789.png";
var typename= objname.split("-");
var again=typename[2];
var again_sep= again.split(".");
var fullNumber =typename[1]+'-'+again_sep[0];

Trim a variable's value until it reaches to a certain character

so my idea is like this..
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
var newString = myString.substr(4); // i want this to dynamically trim the numbers till it has reached the .
// but i wanted the 1. 13. 153. and so on removed.
// i have more value's in my array with different 'numbers' in the beginning
so im having trouble with this can anyone help me find a more simple solution which dynamically chop's down the first character's till the '.' ?
You can do something like
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
songList.forEach(function(value, i){
songList[i] = value.replace(/\d+\./, ''); //value.substr(value.indexOf('.') + 1)
});
Demo: Fiddle
You can use the string .match() method to extract the part up to and including the first . as follows:
var newString = myString.match(/[^.]*./)[0];
That assumes that there will be a match. If you need to allow for no match occurring then perhaps:
var newString = (myString.match(/[^.]*./) || [myString])[0];
If you're saying you want to remove the numbers and keep the rest of the string, then a simple .replace() will do it:
var newString = myString.replace(/^[^.]*. */, "");

Javascript split to split string in 2 parts irrespective of number of spit characters present in string

I want to split a string in Javascript using split function into 2 parts.
For Example i have string:
str='123&345&678&910'
If i use the javascripts split, it split it into 4 parts.
But i need it to be in 2 parts only considering the first '&' which it encounters.
As we have in Perl split, if i use like:
($fir, $sec) = split(/&/,str,2)
it split's str into 2 parts, but javascript only gives me:
str.split(/&/, 2);
fir=123
sec=345
i want sec to be:
sec=345&678&910
How can i do it in Javascript.
var subStr = string.substring(string.indexOf('&') + 1);
View this similar question for other answers:
split string only on first instance of specified character
You can use match instead of split:
str='123&345&678&910';
splited = str.match(/^([^&]*?)&(.*)$/);
splited.shift();
console.log(splited);
output:
["123", "345&678&910"]
You can remain on the split part by using the following trick:
var str='123&345&678&910',
splitted = str.split( '&' ),
// shift() removes the first item and returns it
first = splitted.shift();
console.log( first ); // "123"
console.log( splitted.join( '&' ) ); // "345&678&910"
I wrote this function:
function splitter(mystring, mysplitter) {
var myreturn = [],
myindexplusone = mystring.indexOf(mysplitter) + 1;
if (myindexplusone) {
myreturn[0] = mystring.split(mysplitter, 1)[0];
myreturn[1] = mystring.substring(myindexplusone);
}
return myreturn;
}
var str = splitter("hello-world-this-is-a-test", "-");
console.log(str.join("<br>"));
//hello
//world-this-is-a-test​​​
The output will be either an empty array (not match) or an array with 2 elements (before the split and everything after)
Demo
I have that:
var str='123&345&678&910';
str.split('&',1).concat( str.split('&').slice(1).join('&') );
//["123", "345&678&910"]
str.split('&',2).concat( str.split('&').slice(2).join('&') );
//["123", "345", "678&910"];
for convenience:
String.prototype.mySplit = function( sep, chunks) {
chunks = chunks|=0 &&chunks>0?chunks-1:0;
return this.split( sep, chunks )
.concat(
chunks?this.split( sep ).slice( chunks ).join( sep ):[]
);
}
What about the use of split() and replace()?:
Given we have that string str='123&345&678&910' We can do
var first = str.split("&",1); //gets the first word
var second = str.replace(first[0]+"&", ""); //removes the first word and the ampersand
Please note that split() returns an array that is why getting the index with first[0] is recommended, however, without getting the index, it still worked as needed i.e first+"&".
Feel free to replace the "&" with the string you need to split with.
Hope this helps :)

Categories

Resources