How to handle Querystring in JavaScript? - javascript

I have a js code:
window.onload = function() {
document.getElementById("Button1").onclick = function() {
var t1 = document.getElementById("Text1").value;
var t2 = document.getElementById("Text2").value;
document.URL = 'myurl?t1=' + t1 + '&t2' + t2;
}
}
Here i am adding t1,t2 as query param..now my question is lets say i have entered some data in Textbox1 but not in textbox2, in that case the url I am getting is
'myurl?t1=' + value of textbox1 + '&t2' + This will be blank;
I want to make it dynamic, i.e.if there is not value in Textbox2 then I dont want to append queryparam t2, same goes for t1 also..isit possible?

Use if clauses.
var url = "";
if (t1)
url += "&t1=" + encodeURIComponent(t1);
if (t2)
url += "&t2=" + encodeURIComponent(t2);
document.URL = "myurl" + url.replace(/^&/, "?");
Or even better, don't use JavaScript at all. Just use a form with action="get". This is exactly what they're for.

document.URL = 'myurl?t1=' + t1 + (''!=t2 ? '&t2' + t2 : '');
simply, use (? true:false) logic construction to test if var t2 is empty or not. If it's not empty add to document.URL '&t2'+t2, otherwise pass nothing.

document.URL = 'myurl?t1=' + t1 + (t2?'&t2' + t2:'');

I personally use this function for creating queries:
function CreateQuery(URL, D) {
// Returns a URL in format "URL?Key1=Value1&Key2=Value2"
var L = [];
for (var k in D) {
if (!D.hasOwnProperty(k)) continue;
var eK = encodeURIComponent(k);
var eV = encodeURIComponent(D[Key]);
L.push(eK+'='+eV);
}
if (L.length)
return URL+'?'+L.join('&');
return URL;
}
To use it, you might go e.g:
var q = {};
if (t1) q['t1'] = t1;
if (t2) q['t2'] = t2;
window.location = CreateQuery('myurl', a);
(Or use a <form>, which is probably still the better option as another user has suggested :-)

Related

JavaScript: Remove value from URL search parameter

I've this URL here:
http://localhost.com/?color=Red,Blue,Green
The URL can also have this format:
http://localhost.com/?color=Red,Green,Blue
I'm trying now to remove the value Green from the URL including the , if it acts as separator. I've tried this RegExp here:
var name = 'Green';
var re = new RegExp('(' + name + ',|' + name + ')');
var newUrl = window.location.search.replace(re, '');
window.history.pushState(null, null, newUrl);
So what I want to say is, remove Green, or Green so if the Green, can't be found, the second check will be used. But when I run this the URL looks like this:
http://localhost.com/?olor=Red,Green,Blue
It removed the c from the color which is totally strange. I've tested my RegExp online in an tool and the texts were selected but here it don't works. What I'm doing wrong again?
Update
This is a try with Brunos answer but as you can see sometimes it don't woks:
function replaceColor(search, name) {
var reS = new RegExp(`=${name}(,|$)`);
var reM = new RegExp(`,${name},`);
var reE = new RegExp(`\b${name}$`);
return search
.replace(reS, '=')
.replace(reM, ',')
.replace(reE, '')
.replace(/,$/, '')
}
alert(replaceColor('?size=K,M,S&color=Green,Red,Black', 'Red')) //Works
alert(replaceColor('?size=K,M,S&color=Green,Red,Black', 'Green')) //Works
alert(replaceColor('?size=K,M,S&color=Green,Red,Black', 'Black')) //Don't works
How can I fix this?
Why your example doesn't work:
Your regex looks for green or green,, however in your first example, the URL contains ,green. Being that you only replace the green portion of it, the result is a trailing comma: red,blue,.
It removed the c from the color which is totally strange.
I see nothing in your example that would demonstrate this behavior. I'd assume this is unrelated to the code you've provided.
var name = 'Green';
var re = new RegExp('(' + name + ',|' + name + ')');
var newUrl = "http://localhost.com/?color=Red,Blue,Green".replace(re, '');
console.log(newUrl);
As it seems Bruno has already covered the Regex solution, I'll leave you with a few alternatives.
Using URLSearchParams
You could fetch the param using URLSearchParams, split() the values into an array, filter() out green, and join() them back together.
const urlParams = new URLSearchParams(window.location.search);
const colors = urlParams.get('color');
let result = colors.split(",").filter(n => n != "green").join(",");
If you need to support Internet Explorer, you can reference this answer that includes the following method to retrieve the URL parameters - the result portion can remain the same:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var colors = gerParameterByName("color");
var result = colors.split(",").filter(n => n != "green").join(",");
Just changing your code slightly would do it, but you should probably use Tyler's strategy to manipulate as an array instead
function replaceColor(search, name) {
var reS = new RegExp(`=${name}(,|$)`);
var reM = new RegExp(`,${name},`);
var reE = new RegExp(`[=,]${name}$`);
return search
.replace(reS, '=')
.replace(reM, ',')
.replace(reE, '')
.replace(/,$/, '')
}
var name = 'Green';
var newUrl = replaceColor(window.location.search, name);
window.history.pushState(null, null, newUrl);
Example:
function replaceColor(search, name) {
var reS = new RegExp(`=${name}(,|$)`);
var reM = new RegExp(`,${name},`);
var reE = new RegExp(`[=,]${name}$`);
return search
.replace(reS, '=')
.replace(reM, ',')
.replace(reE, '')
.replace(/,$/, '')
}
console.log(replaceColor('?color=Red,Green,Blue', 'Red'))
console.log(replaceColor('?color=Red,Green,Blue', 'Green'))
console.log(replaceColor('?color=Red,Green,Blue', 'Blue'))
console.log(replaceColor('?color=Red,DarkGreen,Blue', 'Green'))
console.log(replaceColor('?color=DarkGreen', 'Green'))
console.log(replaceColor('?color=Green', 'Green'))
This finally made it:
var reA = new RegExp('Value you want to remove');
var reB = new RegExp('(,&)');
var reC = new RegExp('(,,)');
var reD = new RegExp('(=,)');
var reE = new RegExp('(,$)');
window.history.pushState(null, null, decodeURIComponent(window.location.search).replace(reA, '').replace(reB, '&').replace(reC, ',').replace(reD, '=').replace(reE, ''));
Just enter the value you want to remove or pass a variable here with the value. Should work. For me it does.
Add more condition into your regex
var re = new RegExp('(' + name + ',|' + name + '|,' + name + ')');

Javascript make dynamic links but ignore existing links

Im using this to dynamically make links in a webpage:
var linkWord = function(obj){
for(i in obj){
var x = document.body.innerHTML;
var linkStart = '<a href="'+obj[i]+'">';
var linkEnd = '</a>';
var reg = new RegExp("\\b(" + i + ")\\b","ig");
x = x.replace(reg, linkStart + i + linkEnd);
document.body.innerHTML = x;
}
console.log(obj);
}
linkWord({
'The':'http://www.example.com',
'Vokalia':'http://icant.co.uk',
'Brent':'http://google.com',
});
This creates links in the page that matches the keyword, but overwrites existing hrefs if it also matches. How can I improve this to ignore the existing links?
No jQuery please.
https://jsfiddle.net/o43Lxmtr/
You can fix it by appending negated sets to the reg expression in order to discard words that are prefixed by > and suffixed by <.
Edit: A better approach might be to build a negative lookahead in order to disallow text contained inside tags.
Edit again: it is even better if the negative lookahead only works for anchor tags:
var linkWord = function(obj){
for(i in obj){
var x = document.body.innerHTML;
var linkStart = '<a href="'+obj[i]+'">';
var linkEnd = '</a>';
var reg = new RegExp("\\b(" + i + ")\\b(?![^<]*>|[^<>]*<\/[a])","ig");
x = x.replace(reg, " " + linkStart + i + linkEnd + " ");
document.body.innerHTML = x;
console.log(document.body.innerHTML);
}
console.log(obj);
}
linkWord({
'The':'http://www.example.com',
'Vokalia':'http://icant.co.uk',
'behind':'http://google.com',
});
Note that spaces were also added before and after the replaced string since the regex would strip them.
Edit: working demo here.
Edit2: working demo for second solution here.
Edit3: working demo for third solution here.
It looks like this question was answered before I could come up with a solution, and its also much cleaner than my solution. Good Job
It would seem, after testing your code under various circumstances,
that the best way to accomplish this is to remove your links from
the layout before running your function, and add them again once it is
completed.
Keep in mind we are only removing the inner contents of those
tags, so it will be necessary to store these in order so that they will be added again in the correct places.
JAVASCRIPT
var links_array = {};
var links = document.getElementsByTagName('a');
var linkWord = function(obj){
for(i in obj){
var x = document.body.innerHTML;
var linkStart = '<a class=added href="'+obj[i]+'">';
var linkEnd = '</a>';
var reg = new RegExp("\\b(" + i + ")\\b","ig");
x = x.replace(reg, linkStart + i + linkEnd);
document.body.innerHTML = x;
}
}
function getPrevLinks(){
for(link in links){
if(typeof links[link] === 'object'){
if(! links[link].hasAttribute('class')){
links_array[links[link].innerHTML] = links[link].href;
links[link].innerHTML = '';
}
}
}
return links_array;
}
function returnLinks(links, links_array){
console.log(links);
console.log(links_array);
for(link in links){
if (links[link].innerHTML === ""){
for(prop in links_array){
if(links[link].innerHTML === ""){
links[link].innerHTML = prop;
delete links_array[prop];
}
}
}
}
}
getPrevLinks();
linkWord({
'The':'http://www.example.com',
'Vokalia':'http://icant.co.uk',
'Brent':'http://google.com',
});
returnLinks(links, links_array);
HTML
<body>
<p id=me>The Vokalia Brent some more stuff and
The Vokalia Brent 1
The Vokalia Brent 2
The Vokalia Brent 3
<p>some paragraph</p></p>
<script src="java.js"></script>
</body>
If you need a detailed explanation just leave me a comment.
And the fiddle

Javascript Regex first character after occurence

I have a pager with this url: news?page=1&f[0]=domain_access%3A3".
I need a regex to replace the page=1 with page=2
The 1 and 2 are variable, so I need to find page= + the first character after that.
How can I do that
#EDIT:
from the answers, I distilled
var url = $('ul.pager .pager-next a').attr("href");
var re = /page=(\d+)/i;
var page = url.match(re);
var splitPage = page[0].split("=");
var pageNumber = parseInt(splitPage[1]);
pageNumber += 1;
var nextPagePart = 'page=' + pageNumber;
var nextPageUrl = url.replace(re, nextPagePart);
$('ul.pager .pager-next a').attr("href", nextPageUrl);
There might be a shorter approach ?
Like this:
var url = 'news?page=1&f[0]=domain_access%3A3"';
var page = 2;
url = url.replace(/page=\d+/, 'page=' + page);
EDIT
To achieve what did in your edit:
var obj = $('ul.pager .pager-next a');
var url = obj.attr('href');
url = url.replace(/page=\d+/, 'page=' + (++url.match(/page=(\d+)/)[1]));
obj.attr('href', url);
If you want to replace only a page number and leave the rest You can try something like this:
s/\(.*\)page=\d{1,}\(.*\)/\1number_to_replace\2/

How to get the parameter value from URL in Jquery?

Hi all i have an url where i need to get an parameter from the url
var URL="http://localhost:17775/Students/199/Kishore"
//here from the url i need to get the value 199
this is what i had been trying but the value is null here
function getURLParameter(name) {
return parent.decodeURI((parent.RegExp(name + /([^\/]+)(?=\.\w+$)/).exec(parent.location.href) || [, null])[1]);
};
$(document).ready(function() {
getURLParameter("Students");
//i need to get the value 199 from the url
});
jQuery is not needed for this, though it could be used. There are lots of ways to skin this cat. Something like this should get you started in the right direction:
var URL="http://localhost:17775/Students/199/Kishore";
var splitURL = URL.split("/");
var studentValue = "";
for(var i = 0; i < splitURL.length; i++) {
if(splitURL[i] == "Students") {
studentValue = splitURL[i + 1];
break;
}
}
Here's a working fiddle.
Edit
Based on the comments, indicating that the position will always be the same, the extraction is as simple as:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.split("/")[4];
This is what you're looking for since the URL parameter will keep changing:
http://jsbin.com/iliyut/2/
var URL="http://localhost:17775/Students/199/Kishore"
var number = getNumber('Students'); //199
var URL="http://localhost:17775/Teachers/234/Kumar"
var number = getNumber('Teachers'); //234
function getNumber(section) {
var re = new RegExp(section + "\/(.*)\/","gi");
var match = re.exec(URL);
return match[1];
}
I would do the following:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.match('/Students/(\\d+)/')[1]; //199

Is there a way to remove %20 from dynamically created breadcrumbs?

So, I was messing around with this Dynamic Breadcrumbs write-up, and came across an issue where if the directory name has a space in it, then %20 gets added to the actual visible breadcrumb. Would this be removed using the decodeURI() function or is there a better way?
Here's the js:
var crumbsep = " • ";
var precrumb = "<span class=\"crumb\">";
var postcrumb = "</span>";
var sectionsep = "/";
var rootpath = "/"; // Use "/" for root of domain.
var rootname = "Home";
var ucfirst = 1; // if set to 1, makes "directory" default to "Directory"
var objurl = new Object;
// Grab the page's url and break it up into directory pieces
var pageurl = (new String(document.location));
var protocol = pageurl.substring(0, pageurl.indexOf("//") + 2);
pageurl = pageurl.replace(protocol, ""); // remove protocol from pageurl
var rooturl = pageurl.substring(0, pageurl.indexOf(rootpath) + rootpath.length); // find rooturl
if (rooturl.charAt(rooturl.length - 1) == "/") //remove trailing slash
{
rooturl = rooturl.substring(0, rooturl.length - 1);
}
pageurl = pageurl.replace(rooturl, ""); // remove rooturl from pageurl
if (pageurl.charAt(0) == '/') // remove beginning slash
{
pageurl = pageurl.substring(1, pageurl.length);
}
var page_ar = pageurl.split(sectionsep);
var currenturl = protocol + rooturl;
var allbread = precrumb + "" + rootname + "" + postcrumb; // start with root
for (i=0; i < page_ar.length-1; i++)
{
var displayname = "";
currenturl += "/" + page_ar[i];
if (objurl[page_ar[i]])
{
displayname = objurl[page_ar[i]];
}
else
{
if (ucfirst == 1)
{
displayname = page_ar[i].charAt(0).toUpperCase() + page_ar[i].substring(1);
}
else
{
displayname = page_ar[i];
}
}
if ( i < page_ar.length -2 )
{
allbread += precrumb + crumbsep + "" + displayname + "" + postcrumb;
}
else
{
allbread += crumbsep + displayname;
}
}
document.write(allbread);
If decodeURI() was to be used, where exactly would it go? Also, more unrelated, would there be an option you could add to the code above that would make the actual page inside of the directory be included in the breadcrumbs as the last item instead of the last directory? Not real important but thought I would ask as well. Thanks for any input!
Yes, decodeURI will do the trick. You can add the line displayname = decodeURI(displayname); right before the if that reads if ( i < page_ar.length -2 ):
...
displayname = decodeURI(displayname);
if ( i < page_ar.length -2 )
...
Note that since displayname and currenturl end up being directly embedded in a raw HTML string, any special HTML characters should be escaped first, otherwise you're open to some XSS attacks (imagine some malicious individual posting a link to your site like yoursite.com/valid/page/%3Cscript%3Ealert%28%22Oh%20no%2C%20not%20XSS%21%22%29%3C%2Fscript%3E). One of the simplest ways to do so is covered by this answer, though it requires jQuery.
If you want the current page included in the breadcrumbs, I believe it is sufficient to change the loop to go from 0 to page_ar.length instead of page_ar.length - 1:
...
for (i=0; i < page_ar.length; i++)
...
You should use decodeURIComponent(), not decodeURI() for this. It's a little hard to see what you're trying to do, but here's some simpler code that will give you an array of the 'directories' in the current URI, decoded:
var dirs = location.pathname.split('/');
for (var i=0,len=dirs.length;i<len;++i){
dirs[i] = decodeURIComponent(dirs[i]);
}

Categories

Resources