Replacing value with Regex - javascript

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))

Related

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='));

Can't put index value inside brackets using RegEx

There are two strings. I'm trying to put index value inside empty brackets:
var capacity = 'room[price_group_ids][][capacity]';
var group = 'room[price_group_ids][][group][%s][]';
For example, If an index is 1, they should be:
var capacity = 'room[price_group_ids][1][capacity]';
var group = 'room[price_group_ids][1][group][%s][]';
And if the index is 2, they should look like as the following:
var capacity = 'room[price_group_ids][2][capacity]';
var group = 'room[price_group_ids][2][group][%s][]';
What I've tried and it gives unexpected result:
var index = 2;
var capacity = 'room[price_group_ids][][capacity]'.replace(/\[(.+?)\]/g, "[" + index +"]"); // Should become room[price_group_ids][2][capacity]
var group = 'room[price_group_ids][][group][%s][]'.replace(/\[(.+?)\]/g, "[" + index +"]"); // Should become room[price_group_ids][2][group][%s][]
I'm not good at RegEx and looking for an advice on how to resolve that
A simple replace should work here.
This will only replace the first occurrence of [], so you don't have to worry about others. g flag is used to replace globally i-e all the occurrences of the specified value
capacity.replace('[]', `[${index}]`);
var index = 2;
var capacity = 'room[price_group_ids][][capacity]';
var group = 'room[price_group_ids][][group][%s][]';
capacity = capacity.replace('[]', `[${index}]`);
group = group.replace('[]', `[${index}]`);
console.log(capacity)
console.log(group)
Since you want to match first occurrence of [] so don't use g flag. Also no need to match anything else (.+?) , just /\[\]/ is enough.
Another way is to simply replace string [] with [1]
let index = 2
console.log('room[price_group_ids][][capacity]'.replace(/\[\]/, `[${index}]`));
console.log('room[price_group_ids][][group][%s][]'.replace(/\[\]/, `[${index}]`));
The reg exp /\[(.+?)\]/g matches 1-or-more of anything between [] brackets. You want to detect [ and ] right next to each other; simply:
/\[\]/
Also, you want to ditch the g at the end, unless you want the replacement to occur for all occurrences of [] -- the g means global.
But there are non-regex approaches, too, as shown in the other answers.

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