Regex not working to remove string/whatever - javascript

How can I remove this string from href and update it ?
Example Url:
"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People"
What I am trying:
var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace('/(' + stringToRemove + '\/\w+,)/g', '');
$("#qUrl").attr("href", url);
What I want:
"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,ID,People/FirstName,People/LastName&$expand=People"
Update
Please don't hard code

If you are looking to remove all Products/..., than RegEx is /Products\/.*?,/g
Take a note that RegExp is written as is - without surrounding it with quotes.
var str = 'localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People';
console.log(str.replace(/Products\/\w+,?/g, ''));
/**
* Replace with variable string
*/
var key = 'Products'; // Come from external source, not hardcoded.
var pattern = new RegExp(key+'/\\w+,?', 'g'); // Without start and end delimiters!
console.log(str.replace(pattern, ''));

var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace(/Products\/Name,/g, '');
$("#qUrl").attr("href", url);
Modify the replace call , use regex without quotes

Related

Replace the some special symbol from query string in javascript

I want to get these type of params PropertyType[] in my url instead of PropertyType[0].How to replace it?
Actual URL
City=Antwerp,Archbold,Berkey&PropertyType[0]=Residential&minbed=1&minbath=1&min_price=10000&max_price=2500000
I want these type of url
City=Antwerp,Archbold,Berkey&PropertyType[]=Residential&minbed=1&minbath=1&min_price=10000&max_price=2500000
var serializeData = $('#searchstring').val();
console.log(serializeData);
var data = JSON.stringify(serializeData);
var url1 = data.replace(/['"]/g,'');
var url = url1.replace(/\+/g,' ');
var uri_dec = decodeURIComponent(url);
You can use \d regular expression to replace all digits that appear in []
var url = 'City=Antwerp,Archbold,Berkey&PropertyType[0]=Residential&minbed=1&minbath=1&min_price=10000&max_price=2500000';
var regEx = new RegExp(/\[\d+\]/,'gim');
var newURL = url.replace(regEx, (match) => '[]');
console.log(newURL)
you can replace these using regex in js
url = ""your_url"
new_url = url.replace(/([\d])/g, '')

add to URL after last /

using jQuery; to add something to a url after the last /
for example add sale to:
/gender/category/brand/
so it becomes:
/gender/category/brand/sale
However due to the way the URL's are generated and built I can't just always say 'add it to the end of a URL' as there are sometimes ?query strings on the end for example:
/gender/category/brand/?collection=short&colour=red
I just can't figure out how I can add sale after the final / and always before a ?query string if one exists.
Searching through stackoverflow I've seen some bits about extracting content after the last / but not this, is this possible? I really would appreciate help getting this sorted.
EDIT - The solution
Thanks too all for your help but I was able to adapt Shree's answer the easiest to get this which did what I needed:
if(window.location.href.indexOf("sale") > -1) {
} else {
var raw = window.location.href;
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
window.location.href = newUrl;
}
Use substring with lastIndexOf.
var raw = '/gender/category/brand/?collection=short&colour=red';
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
console.log(newUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In vanilla javascript
var a = "/gender/category/brand/?collection=short&colour=red";
var lastIndexPosition = a.lastIndexOf('/');
a = a.substring(0,lastIndexPosition+1)
+"sale"
+a.substring(lastIndexPosition+1 , a.length);
console.log(a);
By using a reusable function in Javascript:
You can use lastIndexOf and get the last '/' index position and append your new data there.
The lastIndexOf() method returns the position of the last occurrence
of a specified value in a string.
Using this you can send any parameter into function there by it is reusable.
function insert(main_string, ins_string, pos) {
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
var url = "/gender/category/brand/?collection=short&colour=red"
url = insert(url, 'sale', url.lastIndexOf("/") + 1)
console.log(url)
Here is a working DEMO
An alternative, use .split("?") to separate at the ? then combine them back, eg:
// Example with querystring
var url = '/gender/category/brand/?collection=short&colour=red'
var parts = url.split("?");
var newurl = parts[0] + "sale" + "?" + (parts[1]||"")
console.log(newurl)
// Test without querystring
var url = '/gender/category/brand/'
var parts = url.split("?");
var newurl = parts[0] + "sale" + (parts[1]||"")
console.log(newurl)
The (parts[1]||"") handles the case where there isn't a querystring.

Issue on URL using Javascript

I get this URL "R+C%20Seetransport%20Hamburg" passing the query string using Javascript , but i need to get the URL in this format "R%2bC+Seetransport+Hamburg" using C#
Code Used:
var listname = $(this).text();
var listname1 = listname.trim();
// var senderElement = e.target;
var afullUrl = '<%=SPContext.Current.Web.Url%>';
var aurl = afullUrl + "/_Layouts/15/RUM/View_Details.aspx?List_Name="+listname1;
window.location = aurl;
If you are looking for %20 to be replaced by + sign then you can do the following:
var listname1 = listname1.replace(/%20/g, "+");
The %20 represents a white space. And %2b represents +(plus sign).
The problem seems to lie in the Urldecoding. You can also try decodeURIComponent() for removing %20 back to whitespace.

remove a specific area from url using jquery

I have a URL such as http://myurleg.com/ar/Message.html and I want to replace ar with en in it, after clicking on it.
It means that if my url is: http://myurleg.com/ar/Message.html
After click it should become: http://myurleg.com/en/Message.html
I just tried
<script>
$(document).ready(function () {
$('#lng_flip').click(function () {
var url = window.location.href.split('/')[0];
});
});
</script>
Can anyone help?
You can user string replace :
var str = "http://myurleg.com/ar/Message.html";
document.write(str);
var res = str.replace("/ar/", "/fr/");
document.write('<br /> Result : ' + res );
var current = location.pathname.substring(1, 3);
var flipped = current == 'en' ? 'ar' : 'en';
location.pathname = '/' + flipped + location.pathname.substring(3);
Try this
var str = 'http://myurleg.com/ar/Message.html';
var txt = str.replace(/ar/i,"en");
Or in your case
var url = window.location.href;
window.location.href = url.replace(/ar/i,"en");
A general solution, supporting any two-letter language code at the beginning of the path, would be:
location.href = location.href.replace(/(\/\/.*?\/)\w{2}(.*)/, '$1en$2');
Though sometimes it makes more sense to only manipulate location.pathname:
location.pathname = location.pathname.replace(/\/\w{2}(.*)/, '/en$1');
Replace ar in split('/') array with en and join it again using join('/')
var url ='http://myurleg.com/ar/Message.html'.split('/');
url[3]='en';
url=url.join('/');
document.write(url);

Extract values from href attribute string using JQuery

I would like to extract values from href attribute string using JQuery
$(this).attr("href")
will give me
?sortdir=ASC&sort=Vendor_Name
What i need is these values parsed into an array
myArray['sort']
myArray['sortdir']
Any ideas?
Thanks!
BTW , I saw somewhere else on SO the following similar idea to be used with a query string.
I could not tweak it for my needs just yet.
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Try the following:
var href = $(this).attr("href")
href = href.replace('?', "").split('&');
var myArr = {};
$.each(href, function(i, v){
var s = v.split('=');
myArr[s[0]] = s[1];
});
DEMO
Try this
function getURLParameter(name, string) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(string)||[,null])[1]
);
}
var string = $(this).attr("href");
alert(getURLParameter("sort",string));
Demo here http://jsfiddle.net/jbHa6/ You can change the var string value and play around.
EDIT
Removed the second example, since that code is not that good and does not serve the purpose.
Perhaps is there a better solution but to be quick I should have do something like that
var url = $(this).attr("href");
url = url.replace("?sortdir=", "");
url = url.replace("sort=", "");
myArray['sort'] = url.split("&")[1]; // Or use a temporary tab for your split
myArray['sortdir'] = url.split("&")[0];
That solution depends if your url is still like ?sortdir=ASC&sort=Vendor_Name
You could use jQuery BBQ's deparam function from here:
http://benalman.com/code/projects/jquery-bbq/examples/deparam/

Categories

Resources