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

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

Related

Change strings in Javascript with replace() based on index

I have the following string
let string = "01,15,01,45"
Which i want to turn to this
string = "01:15 - 01:45"
but i'm only able to come up with
"01,15,01,45".replace(/,/g, ':') // Gives "01:15:01:45"
but then i'm not sure how to get the index of the 5th position in string and replace it to ' - '
Any suggestion will be helpful.
Don't try doing things in one step when it would be clearer as multiple steps.
let string = "01,15,01,45";
let parts = string.split(",");
let result = `${parts[0]}:${parts[1]} - ${parts[2]}:${parts[3]}`;
let string = "01,15,01,45";
stringArray=string.split(',');
firstInterval=stringArray.slice(0, stringArray.length/2);
Output: ["01", "15"]
secondInterval=stringArray.slice(stringArray.length/2,stringArray.length);
Output:["01", "45"]
firstIntervalString=firstInterval[0]+":"+firstInterval[1];
Output: "01:15"
secondIntervalString=secondInterval[0]+":"+secondInterval[1];
Output: "01:45"
completeInterval=firstIntervalString+" - "+secondIntervalString;
Output: "01:15 - 01:45"
I think the code is self-explanatory. Still, please feel free to let me know if any part is not clear.
Another approach with matching pairs and replacing leftover commas.
let string = "01,15,01,45",
result = string.match(/\d\d,\d\d/g).map(p => p.replace(/\,/, ':')).join(' - ');
console.log(result);

Extract part of a string which start with a certain word in Javascript

I have the following string
"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,
I need to get string after "ssu":" the Result should be 89c4eef0-3a0d-47ae-a97f-42adafa7cf8f. How do I do it in Javascript but very simple? I am thinking to collect 36 character after "ssu":".
You could build a valid JSON string and parse it and get the wanted property ssu.
var string = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,',
object = JSON.parse(`{${string.slice(0, -1)}}`), // slice for removing the last comma
ssu = object.ssu;
console.log(ssu);
One solution would be to use the following regular expression:
/\"ssu\":\"([\w-]+)\"/
This pattern basically means:
\"ssu\":\" , start searching from the first instance of "ssu":"
([\w-]+) , collect a "group" of one or more alphanumeric characters \w and hypens -
\", look for a " at the end of the group
Using a group allows you to extract a portion of the matched pattern via the String#match method that is of interest to you which in your case is the guid that corresponds to ([\w-]+)
A working example of this would be:
const str = `"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,`
const value = str.match(/\"ssu\":\"([\w-]+)\"/)[1]
console.log(value);
Update: Extract multiple groupings that occour in string
To extract values for multiple occurances of the "ssu" key in your input string, you could use the String#matchAll() method to achieve that as shown:
const str = `"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,"ssu":"value-of-second-ssu","ssu":"value-of-third-ssu"`;
const values =
/* Obtain array of matches for pattern */
[...str.matchAll(/\"ssu\":\"([\w-]+)\"/g)]
/* Extract only the value from pattern group */
.map(([,value]) => value);
console.log(values);
Note that for this to work as expected, the /g flag must be added to the end of the original pattern. Hope that helps!
Use this regExp: /(?!"ssu":")(\w+-)+\w+/
const str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,';
const re = /(?!"ssu":")(\w+-)+\w+/;
const res = str.match(re)[0];
console.log(res);
You can use regular expressions.
var str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,'
var minhaRE = new RegExp("[a-z|0-9]*-[a-z|0-9|-]*");
minhaRE.exec(str)
OutPut: Array [ "89c4eef0-3a0d-47ae-a97f-42adafa7cf8f" ]
Looks almost like a JSON string.
So with a small change it can be parsed to an object.
var str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049, ';
var obj = JSON.parse('{'+str.replace(/[, ]+$/,'')+'}');
console.log(obj.ssu)

Javascript regex capture giving unexpected results

I am trying to capture all data before the first _. What I have so far is
const regex = /(.*)(?=_)/g;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
The output is an array Array ["Mike_Jones","" ]
What I was expecting was Mike
Use /^[^_]*/
^ looks from the beginning of the string
[^_] negates the _
* gives any number of characters
const regex = /^[^_]*/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
var s = "Mike_Jones_Jr";
console.log(s.split('_')[0]);
Create a capture group ((something between parentheses)) that starts at the beginning of the line (^) and is lazy (.*?), then grab the second item in the matching array.
const regex = /(^.*?)_/s
console.log('Mike_Jones_Jr'.match(regex)[1] || '')
console.log(`Mike
_Jones_Jr`.match(regex)[1] || '')
You can simply use split,
Note:- Second parameter is to limit the number of elements in final outptut
var s = "Mike_Jones_Jr";
console.log( s.split('_', 1) );
If you want to do using regex, you can drop the g flag
const regex = /^[^_]*(?=_)/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
console.log("_ melpomene is awesome".match(regex));

replace a string partially with something else

lets say I have this image address like
https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
how is it possible to replace FILE_NAME.jpg with THUMB_FILE_NAME.jpg
Note: FILE_NAME and THUMB_FILE_NAME are not static and fix.
the FILE_NAME is not fixed and I can't use string.replace method.
eventually I don't know the File_Name
Use replace
.replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME")
or if you want to support multiple formats
.replace(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g, "THUMB_FILE_NAME")
Demo
var output = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b".replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME");
console.log( output );
Explanation
(?<=\/) matches / but doesn't remember the match
[^\/]* matches till you find next /
(?=(.jpg) ensures that match ends with .jpg
To match the FILE_NAME, use
.match(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g)
var pattern = /[\w-]+\.(jpg|png|txt)/
var c = 'https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
'
c.replace(pattern, 'YOUR_FILE_NAME.jpg')
you can add any format in the pipe operator
You can use the String's replace method.
var a = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
a = a.replace('FILE_NAME', 'THUMB_FILE_NAME');
If you know the format, you can use the split and join to replace the FILE_NAME.
let str = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
let str_pieces = str.split('/');
let str_last = str_pieces[str_pieces.length - 1];
let str_last_pieces = str_last.split('?');
str_last_pieces[0] = 'THUMB_' + str_last_pieces[0];
str_last = str_last_pieces.join('?');
str_pieces[str_pieces.length - 1] = str_last;
str = str_pieces.join('/');

Cut text using jquery

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.

Categories

Resources