Removing last forwardslash and the text before it - javascript

I have an URL looking like this:
https://www.website.com/dk/da/home/category/
I am trying to remove the last forward slash and the text before it, untill it reaches the new forwardslash. Meaning i would like the new URL to look like this:
https://www.website.com/dk/da/home/
I am trying to use substring to achieve this, but i run into problems because I always have a forward slash at the end of the URL.
var to = url.lastIndexOf('/');
to = to == -1 ? url.length : to + 1;
newUrl = url.substring(0, to);

Use regex
let url = "https://www.website.com/dk/da/home/category/"
url = url.replace(/\w+\/$/, "")
console.log(url)
Explanation of the given example: https://regex101.com/r/3Nw7sL/2
UPDATE: as pointed out by #CertainPerformance in the comments of this answer, it is even easier to search for the last part of the url (\w+/) and replace it with an empty string.

string.lastIndexOf can take a second parameters indicating from which index the search must be done (starting from the end)
so you can do this to get the last which is not the last character of the string :
let url = "https://www.website.com/dk/da/home/category/"
var to = url.lastIndexOf('/', url.length - 2);
to = to == -1 ? url.length : to + 1;
newUrl = url.substring(0, to);
console.log(newUrl)

other way:
str='https://www.website.com/dk/da/home/category/';
arr = str.split('/');
arr.pop();
arr.pop();
str = arr.join('/');
str = str + '/';

How about executing same logic twice :
public static void main(String[] args)
{
String url = "https://www.website.com/dk/da/home/category/";
int to = url.lastIndexOf('/');
to = to == -1 ? url.length() : to;
String newUrl = url.substring(0, to);
to = newUrl.lastIndexOf('/');
to = to == -1 ? newUrl.length() : to;
newUrl = url.substring(0, to);
System.out.println(newUrl);
}
PS - Don't write it the logic twice instead use methods.

Related

Can't get lastIndexOf to work

I have this code
var url = 'http://sitename.com/category/diving/',
catName = url.substr(url.lastIndexOf('/') + 1);
And when I try to run alert(catName) it returns empty string. What am I doing wrong?
You need the category name but you have to remove first the last /:
var url = 'http://sitename.com/category/diving/';
url = url.substr(0, url.length - 1);
catName = url.substr(url.lastIndexOf('/') + 1);
Result:
"diving"
because you add +1 to the index, so you get undefined string. remove the +1 in the lastIndexOf
You can use..parseUri
var url = 'http://sitename.com/category/diving/';
url = url.substr(0, url.length - 1);
var filename1 = parseUri(url ).file;--way1
var filename2 = url.match(/.*\/(.*)$/)[1];
Result="diving";
Ways to achieve this

How to replace second specific character in url using jquery

I have the following url to work with:
...login?returnUrl=%2F%2Fprint?newdata=%test1234
I need to replace the second(last) ' ? ' by an ampersand
Please help..
You could;
url = url.replace(/\?([^\?]*)$/g, '&$1')
var url = 'your url';
//GET INDEX OF FIRST "?" CHARACTER
var index = url.indexOf("?");
//FIRST PART OF URL (BEFORE AND INCLUDING THE FIRST "?" CHARACTER)
var first_part = url.substring(0,(index+1));
//SECOND PART OF STRING (AFTER AND EXCLUDING THE FIRST "?" CHARACTER)
var second_part = url.substring((index+1), url.length);
//SECOND PART REPLACE "?" WITH "&"
var second_part_replace = second_part.replace("?","&");
//YOUR FINAL URL
var new_string = first_part+""+second_part_replace;
var count = 0;
str.replace(/\?/g, function () { return count++ == 0 ? '?' : '&'; });
var parts = url.split('?');
url = parts.slice(0, parts.length - 2).join('?') +'&'+parts[parts.length - 1];
Using slice, split and join you can achieve that. Or using some regular expressions.
Try this (targets the second one) :
var url = 'login?returnUrl=%2F%2Fprint?newdata=%test1234';
var index = url.indexOf('?', url.indexOf('?') + 1);
if (index !== -1) url = url.slice(0, index) + '&' + url.slice(index + 1);
Or this (targets the last one) :
var url = 'login?returnUrl=%2F%2Fprint?newdata=%test1234';
url = url.replace(/\?(?=[^\?]*$)/, '&');

Javascript: String search for regex, starting at the end of the string

Is there a javascript string function that search a regex and it will start the search at the end?
If not, what is the fastest and/or cleanest way to search the index of a regex starting from the end?
example of regex:
/<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi
Maybe this can be useful and easier:
str.lastIndexOf(str.match(<your_regex_here>).pop());
Perhaps something like this is suitable for you?
Javascript
function lastIndexOfRx(string, regex) {
var match = string.match(regex);
return match ? string.lastIndexOf(match.slice(-1)) : -1;
}
var rx = /<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi;
console.log(lastIndexOfRx("", rx));
console.log(lastIndexOfRx("<i>it</i><b>bo</b>", rx));
jsFiddle
And just for interest, this function vs the function that you choose to go with. jsperf
This requires that you format your regex correctly for matching exactly the pattern you want and globally (like given in your question), for example /.*(<\/?([a-z][a-z0-9]*)\b[^>]*>?)/i will not work with this function. But what you do get is a function that is clean and fast.
You may create a reverse function like:
function reverse (s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
and then use
var yourString = reverse("Your string goes here");
var regex = new Regex(your_expression);
var result = yourString.match(regex);
Another idea: if you want to search by word in reverse order then
function reverseWord(s) {
var o = '';
var split = s.split(' ');
for (var i = split.length - 1; i >= 0; i--)
o += split[i] + ' ';
return o;
}
var yourString = reverseWord("Your string goes here");
var regex = new Regex(your_expression);
var result = yourString.match(regex);
Andreas gave this from the comment:
https://stackoverflow.com/a/274094/402037
String.prototype.regexLastIndexOf = function(regex, startpos) {
regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
if(typeof (startpos) == "undefined") {
startpos = this.length;
} else if(startpos < 0) {
startpos = 0;
}
var stringToWorkWith = this.substring(0, startpos + 1);
var lastIndexOf = -1;
var nextStop = 0;
while((result = regex.exec(stringToWorkWith)) != null) {
lastIndexOf = result.index;
regex.lastIndex = ++nextStop;
}
return lastIndexOf;
}
Which gives the functionality that I need, I tested my regex, and it is successful. So I'll use this
It depends what you exactly want to search for. You can use string.lastIndexOf or inside the regexp to use $ (end of the string).
Update:
try the regexp
/<\/?([a-z][a-z0-9]*)\b[^>]*>?[\w\W]*$/gi
var m = text.match(/.*(<\/?([a-z][a-z0-9]*)\b[^>]*>?)/i);
if (m) {
textFound = m[1];
position = text.lastIndexOf(textFound);
}
Use .* to skip as much text as posible, capture the text found and search it with lastIndexOf
EDIT:
Well, if text is found, no need to search with lastIndexOf. m[0] contains the full coincidence (including all the initial padding), and m[1] the searched text. So position of found text is m[0].length - m[1].length
var m = text.match(/.*(<\/?([a-z][a-z0-9]*)\b[^>]*>?)/i);
if (m) {
textFound = m[1];
position = m[0].length - m[1].length;
}
Assuming you're looking for a string 'token', then you need the position of 'token' that has no other 'token' following until the end of the string.
So you should compose your regex something like that:
$token = 'token';
$re = "/(?:$token)[^(?:$token)]*$/";
This will find your 'token' where no further 'token' can be found until string end. The "(?:" grouping simply makes the group non-storing, slightly speeding up performance and saving memory.

Javascript Reg Expression to replace Get Parameter in the URL

Using a regular expression, I want to write a function that will take a URL and a parameter name: ReplaceParamValueinURL (url, param, value).
If the parameter exists, it will replace the value in the URL.
If the parameter doesn't exist, it will add it to the URL along with the value.
If the parameter exists with no value, it will add the value to the parameter.
Is there an elegant way of doing all three in regex find and replace?
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, a , 4)
returns http://google.com?a=4&b=2&c=3
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, a , 4)
returns http://google.com?a=4&b=2&c=3
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, c , 4)
returns http://google.com?a=1&b=2&c=4
ReplaceParamValueinURL ("http://google.com?a=1&b=2&c=3, d , 5)
returns http://google.com?a=1&b=2&c=3&d=5
ReplaceParamValueinURL ("http://google.com?aaa=0&a=1&b=2&c=3, a , 6)
returns http://google.com?aaa=0&a=6&b=2&c=3
ReplaceParamValueinURL ("http://google.com?a=1&b&c=3, b , 2)
returns http://google.com?a=1&b=2&c=3
I am hoping to do this with Reg ex instead of split. I really appreciate it if you can explain your answer if the regex is too complex. Is there a jQuery function that already does this?
I guess it's a very common case but can have many corner cases.
ReplaceParamValueinURL ("http://google.com?a=1&b&c=3#test, a , 2)
returns http://google.com?a=2&b&c=3#test
No you can't do it with a single regexp, but the function is pretty simple, i've tested it with all your examples so it should work:
function ReplaceParamValueinURL (url, name, val) {
//Try to replace the parameter if it's present in the url
var count = 0;
url = url.replace(new RegExp("([\\?&]" + name + "=)[^&]+"), function (a, match) {
count = 1;
return match + val;
});
//If The parameter is not present in the url append it
if (!count) {
url += (url.indexOf("?") >=0 ? "&" : "?") + name + "=" + val;
}
return url;
}
try this,
function ReplaceParamValueinURL(url , replceparam , replaceValue)
{
regExpression = "(\\?|&)"+replceparam+"(=).(&|)";
var regExpS = new RegExp(regExpression, "gm");
var getmatch = url.match(regExpS);
var regExpSEq = new RegExp("=", "g");
var getEqalpostion = regExpSEq.exec(getmatch);
var newValue;
if(getmatch[0].charAt(getmatch[0].length - 1) != "&")
{
var subSrtingToReplace = getmatch[0].substring((getEqalpostion.index+ 1),getmatch[0].length );
newValue = getmatch[0].replace(subSrtingToReplace , replaceValue);
}
else
{
var subSrtingToReplace = getmatch[0].substring((getEqalpostion.index+ 1) , getmatch[0].length - 1 );
newValue = getmatch[0].replace(subSrtingToReplace , replaceValue);
}
return returnString = url.replace(regExpS , newValue);
}

Search and replace specific query string parameter value in javascript

I have a string which is something like this :
a_href= "www.google.com/test_ref=abc";
I need to search for test_ref=abc in thisabove strinng and replace it with new value
var updated_test_ref = "xyz";
a_href ="www.google.com/test_ref=updated_test_ref"
i.e
www.google.com/test_ref=xyz.
How can we do this ?
EDIT:
test_ref value can be a URL link in itself something like http://google.com?param1=test1&param2=test2. I need to capture complete value not till first &.
a_href = a_href.replace(/(test_ref=)[^\&]+/, '$1' + updated_test_ref);
Based on this discussion I have fixed the Chris function (problem with regex string!)
function updateUrlParameter(url, param, value){
var regex = new RegExp('('+param+'=)[^\&]+');
return url.replace( regex , '$1' + value);
}
Based on this discussion I have created a references function. enjoy
updateUrlParameter(url, param, value){
var regex = new RegExp("/([?|&]" + param + "=)[^\&]+/");
return url.replace(regex, '$1' + value);
}
I was searching for this solution for few hours and finally stumbled upon this question. I have tried all the solutions here. But there is still an issue while replacing specific param value in url.
Lets take a sample url like
http://google.com?param1=test1&param2=test2&anotherparam1=test3
and the updated url should be like
http://google.com?param1=newtest&param2=test2&anotherparam1=test3, where value of param1 is changed.
In this case, as #Panthro has pointed out, adding [?|&] before the querying string ensures that anotherparam1 is not replaced. But this solution also adds the '?' or '&' character to the matching string. So while replacing the matched characters, the '?' or '&' will also get replaced. You will not know exactly which character is replaced so you cannot append that character as well.
The solution is to match '?' or '&' as preceding characters only.
I have re-written the function of #Chris, fixing the issue with string and have added case insensitive argument.
updateUrlParameter(url, param, value){
var regex = new RegExp('(?<=[?|&])(' + param + '=)[^\&]+', 'i');
// return url.replace(regex, param + '=$1' + value);
return url.replace(regex, param + '=' + value);
}
Here (?<=[?|&]) means, the regex will match '?' or '&' char and will take the string that occurs after the specified character (looks behind the character). That means only param1=test1 substring will be matched and replaced.
I know this is a bit dirty code but I've achieved what I was looking for. It replaces the given query string or adds new one if it doesn't exist yet.
function updateUrlParameter(url, param, value) {
var index = url.indexOf("?");
if (index > 0) {
var u = url.substring(index + 1).split("&");
var params = new Array(u.length);
var p;
var found = false;
for (var i = 0; i < u.length; i++) {
params[i] = u[i].split("=");
if (params[i][0] === param) {
params[i][1] = value;
found = true;
}
}
if (!found) {
params.push(new Array(2));
params[params.length - 1][0] = param;
params[params.length - 1][1] = value;
}
var res = url.substring(0, index + 1) + params[0][0] + "=" + params[0][1];
for (var i = 1; i < params.length; i++) {
res += "&" + params[i][0] + "=" + params[i][1];
}
return res;
} else {
return url + "?" + param + "=" + value;
}
}
It will work when given regular URL addresses like:
updateUrlParameter('https://www.example.com/some.aspx?mid=1&id=2','id','5');
updateUrlParameter('https://www.example.com/?mid=1&id=2','id','5');
updateUrlParameter('https://www.example.com/some.aspx','id','5');
Please note It will NOT work only if any of the query string parameter name or value contains "=" and/or "&" chars. It will work just fine behind that.
*Java script code to find a specific query string and replace its value *
('input.letter').click(function () {
//0- prepare values
var qsTargeted = 'letter=' + this.value; //"letter=A";
var windowUrl = '';
var qskey = qsTargeted.split('=')[0];
var qsvalue = qsTargeted.split('=')[1];
//1- get row url
var originalURL = window.location.href;
//2- get query string part, and url
if (originalURL.split('?').length > 1) //qs is exists
{
windowUrl = originalURL.split('?')[0];
var qs = originalURL.split('?')[1];
//3- get list of query strings
var qsArray = qs.split('&');
var flag = false;
//4- try to find query string key
for (var i = 0; i < qsArray.length; i++) {
if (qsArray[i].split('=').length > 0) {
if (qskey == qsArray[i].split('=')[0]) {
//exists key
qsArray[i] = qskey + '=' + qsvalue;
flag = true;
break;
}
}
}
if (!flag)// //5- if exists modify,else add
{
qsArray.push(qsTargeted);
}
var finalQs = qsArray.join('&');
//6- prepare final url
window.location = windowUrl + '?' + finalQs;
}
else {
//6- prepare final url
//add query string
window.location = originalURL + '?' + qsTargeted;
}
})
});

Categories

Resources