Javascript - Split and join - Remove first 3 array - javascript

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.

Related

Replacing value with Regex

I have two variables:
var v1 = 'http://localhost/wa/pradeep'
var v2 = 'http://localhost/wa/pradeep/some/text'
var re = /(\/wa\/\w*\/?)/
var replaceValue = '$&/~tag/test'
console.log(v1.replace(re, replaceValue))
console.log(v2.replace(re, replaceValue))
I want to avoid two consecutive slashes from the second output. Can anyone guide me how can I achieve the same?
may be there is a way to conditionally check if second group is present and then add slash? I could not find a way to achieve it.
Edit: For the second case, there should a slash at the end (after 'test') For ex:
http://localhost/wa/pradeep/~tag/test/some/text
You need to keep last / outside group and use back-reference of group #1:
var v1 = 'http://localhost/wa/pradeep'
var v2 = 'http://localhost/wa/pradeep/some/text'
var re = /(\/wa\/\w*)(\/?)/
var replaceValue = '$1/~tag/test$2'
console.log(v1.replace(re, replaceValue))
console.log(v2.replace(re, replaceValue))

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

regex: get string in url login/test

I have a url
https://test.com/login/param2
how do I get the the second parameter "param2" from the url using REGEX?
the url can also be
https://test.com/login/param2/
So the regex should work for both urls.
I tried
var loc = window.location.href;
var locParts = loc.split('/');
and then looping through locParts, but that seems inefficient.
The "param2" can be have number, alphatical character from a-z, and a dash.
Use String#match method with regex /[^\/]+(?=\/?$)/.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var reg = /[^\/]+(?=\/?$)/;
console.log(
a.match(reg)[0],
b.match(reg)[0]
)
Or using String#split get last non-empty element.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var splita = a.split('/'),
splitb = b.split('/');
console.log(
splita.pop() || splita.pop(),
splitb.pop() || splitb.pop()
)
If you don't mind using JS only (so no regex), you can use this :
var lastParameter = window.location.href.split('/').slice(-1);
Basicaly, like you, I fetch the URL, split by the / character, but then I use the splice function to get teh last element of the split result array.
Regular expressions might be compact, but they're certainly not automatically efficient if you can do what you want without.
Here's how you can change your code:
var loc = 'https://test.com/login/facebook/'; // window.location.href;
var locParts = loc.split('/').filter(function(str) {return !!str});
var faceBookText = locParts.pop();
console.log(faceBookText);
The filter removes the last empty item you would get if the url ends with '/'. That's all you need, then just take the last item.

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];

Categories

Resources