Get specific letters between two symbols - javascript

I'm trying to get the letters between two specified symbols.
Example
var a = 'Testing code https://example.com/ABC-BAC tralala'; // I would need to get ABC
var b = 'Depends on x \n https://example.com/CADER-BAC'; // I would need to get CADER
var c ='lots of examples: \n example.com/CAB-BAC'; // I would need to get CAB
var d ='lots of examples: \n https://abc.example.com/CAB-BAC'; // I would need to get CAB
My main problem is that I need a unique syntax that would work for both https:// version or without any https://, therefore using indexOf on '/' wouldn't work that well.
I've tried regex but of course, that only fits one solution:
let regex = /^https://example\.com/[a-zA-Z]+-BAC$/i;
return regex.test(input);
Any help is appreciated, thank you!

You may use match here:
var input = "https://example.com/CADER-BAC";
var code = input.match(/^.*\/([^-]+)-.*$/);
console.log(code[1]);

You can use str.substring in combination of str.lastIndexOf:
const a = 'Testing code https://example.com/ABC-BAC tralala'; // I would need to get ABC
const b = 'Depends on x \n https://example.com/CADER-BAC'; // I would need to get CADER
const c = 'lots of examples: \n example.com/CAB-BAC'; // I would need to get CAB
const getSubstring = (str) => {
return str.substring(
str.lastIndexOf('example.com/') + 'example.com/'.length,
str.lastIndexOf('-'))
}
console.log(getSubstring(a), getSubstring(b), getSubstring(c))

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

Javascript get only matched text in regex

I have string like below
BANKNIFTY-13-FEB-2020-31200-ce
I want to convert the string to 13-FEB-31200-ce
so I tried below code
str.match(/(.*)-(?:.*)-(?:.*)-(.*)-(?:.*)-(?:.*)/g)
But its returning whole string
Two capture groups is probably the way to go. Now you have two options to use it. One is match which requires you to put the two pieces together
var str = 'BANKNIFTY-13-FEB-2020-31200-ce'
var match = str.match(/[^-]+-(\d{2}-[A-Z]{3}-)\d{4}-(.*)/)
// just reference the two groups
console.log(`${match[1]}${match[2]}`)
// or you can remove the match and join the remaining
match.shift()
console.log(match.join(''))
Or just string replace which you do the concatenation of the two capture groups in one line.
var str = 'BANKNIFTY-13-FEB-2020-31200-ce'
var match = str.replace(/[^-]+-(\d{2}-[A-Z]{3}-)\d{4}-(.*)/, '$1$2')
console.log(match)
Regex doesn't seem to be the most appropriate tool here. Why not use simple .split?
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let splits = str.split('-');
let out = [splits[1], splits[2], splits[4], splits[5]].join('-');
console.log(out);
If you really want to use regexp,
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let splits = str.match(/[^-]+/g);
let out = [splits[1], splits[2], splits[4], splits[5]].join('-');
console.log(out);
I would not use Regex at all if you know exact positions. Using regex is expensive and should be done differently if there is way. (https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/)
const strArr = "BANKNIFTY-13-FEB-2020-31200-ce".split("-"); // creates array
strArr.splice(0,1); // remove first item
strArr.splice(2,1); // remove 2020
const finalStr = strArr.join("-");
If the pattern doesn't need to be too specific.
Then just keep it simple and only capture what's needed.
Then glue the captured groups together.
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let m = str.match(/^\w+-(\d{1,2}-[A-Z]{3})-\d+-(.*)$/)
let result = m ? m[1]+'-'+m[2] : undefined;
console.log(result);
In this regex, ^ is the start of the string and $ the end of the string.
You can have something like this by capturing groups with regex:
const regex = /(\d{2}\-\w{3})(\-\d{4})(\-\d{5}\-\w{2})/
const text = "BANKNIFTY-13-FEB-2020-31200-ce"
const [, a, b, c] = text.match(regex);
console.log(`${a}${c}`)

Javascript - Split and join - Remove first 3 array

Link - split and remove first 3 array.
offerlink variable will have multiple urls. But, /content/revamp/en will remain same for all links. Have to remove this from the path name.
offerlink2 - works as expected. But, offerLink1 also getting result by excluding /hotels/india. this is required for this url.
Same code have to work for both offerlInk1 and offerLink2.
JS:
var offerlink = /content/revamp/en/hotels/india/offers/purchase.html
var offerLinkSplit = $offerLink.replace(/\.\w+$/, '').split('/');
var offerLinkTrim = $offerLinkSplit.slice(-2).join('/');
getting output (Wrong) = /offers/purchase
Needed output = /hotels/india/offers/purchase
If below link means /content/revamp/en/offers/quick-deal.html
correct output = /offers/quick-deal
Try using slice(4) to extract past the 4th / in your input:
var $offerLink1 = '/content/revamp/en/hotels/india/offers/purchase.html'
var offerLinkSplit1 = $offerLink1.replace(/\.\w+$/, '').split('/');
var offerLinkTrim1 = '/' + offerLinkSplit1.slice(4).join('/');
console.log(offerLinkTrim1);
Note that strings need to be enclosed in delimiters, and you need to use consistent variable names.
A regular expression alone might be better here, though: match 3 repetitions of /<anything but />, and replace with the empty string:
var $offerLink1 = '/content/revamp/en/hotels/india/offers/purchase.html';
var $offerLink2 = '/content/revamp/en/offers/quick-deal.html';
const re = /(?:\/[^/]+){3}/;
console.log(
$offerLink1.replace(re, ''),
$offerLink2.replace(re, '')
);
var offerlink = /content/revamp/en/hotels/india/offers/purchase.html
var offerLinkSplit = $offerLink.replace(/\.\w+$/, '').split('/');
var offerLinkSplitLength = offerLinkSplit.length;
var offerLinkTrim = offerLinkSplit.slice(4,offerLinkSplitLength).join('/');
If /content/revamp/en always remains the same, simply take the substring
var offerlink1 = '/content/revamp/en/hotels/india/offers/purchase.html';
var removeText = '/content/revamp/en';
console.log(offerlink1.substring(removeText.length))
slice(-2) only takes the last 2 elements.
To remove the first three use slice(3).
See docs for more information.

JS What's the fastest way to display one specific line of a list?

In my Javascript code, I get one very long line as a string.
This one line only has around 65'000 letters. Example:
config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...
What I have to do is replace all & with an break (\n) first and then pick only the line which starts with "path_of_code=". This line I have to write in a variable.
The part with replace & with an break (\n) I already get it, but the second task I didn't.
var obj = document.getElementById('div_content');
var contentJS= obj.value;
var splittedResult;
splittedResult = contentJS.replace(/&/g, '\n');
What is the fastest way to do it? Please note, the list is usually very long.
It sounds like you want to extract the text after &path_of_code= up until either the end of the string or the next &. That's easily done with a regular expression using a capture group, then using the value of that capture group:
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
}
Live Example:
var theString = "config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
console.log(text);
}
Use combination of String.indexOf() and String.substr()
var contentJS= "123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var index = contentJS.indexOf("&path_of_code"),
substr = contentJS.substr(index+1),
res = substr.substr(0, substr.indexOf("&"));
console.log(res)
but the second task I didn't.
You can use filter() and startsWith()
splittedResult = splittedResult.filter(i => i.startsWith('path_of_code='));

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('/');

Categories

Resources