How to replace second specific character in url using jquery - javascript

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(/\?(?=[^\?]*$)/, '&');

Related

Removing last forwardslash and the text before it

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.

Replace the last dash value from a data attribut?

var dataUrl = $('#AjaxMoreStatus').attr("data-url");
// http://localhost:8888/app/status/get/31/7
I need to change the last value of the link from the last dash (7) by another value.
7 is a dynamic value.
Ho can i do it ?
For instance if i want to change the dynamic value 7 by 9 :
var new = 9;
$("#AjaxMoreStatus").attr("data-url", url without the 7 + '/' + new);
use lastIndexOf to check the index of last occurrence of "/"
var dataUrl = $('#AjaxMoreStatus').attr("data-url");
var newValue = 9;
dataUrl = dataUrl.substring( 0, dataUrl.lastIndexOf( "/" ) ) + "/" + newValue;
Use split() to separate the pieces of the url and replace the last item:
var url = "http://localhost:8888/app/status/get/31/7";
url = url.replace("http://", "").split("/");
var newValue = "9";
url[(url.length - 1)] = newValue;
var newUrl = "http://"+url.join("/");
You can use replace method just like here
var url = "http://localhost:8888/app/status/get/31/7";
a.replace(/\/(\d*)$/, '/' + newValue);
If you only need to change the last 7 for other thing, try this code:
var dataUrl = 'http://localhost:8888/app/status/get/31/7';
var newValue = 9;
dataUrl = dataUrl.replace(/([0-9])$/i, newValue);
https://jsfiddle.net/8hf6ra8k/1/
Hope it may help you :).
You can use .lastIndexOf() to find the index. Then you can replace value at that index. For reference, refer following post: How do I replace a character at a particular index in JavaScript?.
var url = "htt[://stacloverflow.com/test/param/tobe/replaced/with/newValue";
var newVal = "testNewValue";
var lastIndex = url.lastIndexOf('/');
var result = url.substring(0,lastIndex+1) + newVal;
alert(result)

How to get the ID from this URL?

I need a way to get the ID ( 153752044713801 in this case ) of this page:
https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801
I tried this code but doen't work:
var str = 0, pagefb = 0;
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var re1 = /^(.+)facebook\.com\/pages\/([-\w\.]+)\/([-\w\.]+)/;
if(re1.exec(fburl)){
str = re1.exec(fburl)[3];
pagefb = str.substr(str.lastIndexOf("-") + 1);
alert('ok');
}
try:
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split("/");
var myId = parts[parts.length-1];
alert(myId);
Try this regular expression: ^(.+)facebook\.com\/pages\/.*\/(\d*)
(in JavaScript, you have to add "/" at the beginning and end of the pattern like you did before)
this works for me
fburl.split('/')[fburl.split('/').length-1]
You can split the string using .split("/"). More information is availible on MDN
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]
Basically it returns an array of the string split into multiple parts (at the character/s you put inside the brackets).
The parts[parts.length - 1] will get the last item in the array parts
Demo below (Don't worry about the document..., they just print out data):
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713‌​801/?ref=sfhsidufh';
var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]
// If first digit is ?
if (myFacebookId[0] == '?') {
// Set myFacebookId to the second from last part
myFacebookId = parts[parts.length - 2]
}
document.write('MyFacebookId: ' + myFacebookId)

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

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