JavaScript: Remove value from URL search parameter - javascript

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

Related

javascript- replace text with part of the file name

I'm trying to create a script in adobe illustrator that will check if a file name contains "ph" +5 numbers.
If it has been found then it will replace a part of a text with the match from the file name.
This is what I have so far I just can't get it to work, the text is replaced with "null"
var doc = app.activeDocument;
var name = doc.name;
var match = name.match(/ph\d{5}/);
for (i = 0; i < doc.textFrames.length; i++)
{
doc.textFrames[i].contents = doc.textFrames[i].contents.replace(/ph00000/gi, match);
}
I'd try this:
var doc = app.activeDocument;
var match = doc.name.match(/ph\d{5}/);
if (match != null) {
for (i = 0; i < doc.textFrames.length; i++) {
doc.textFrames[i].contents = doc.textFrames[i].contents.replace(/ph00000/gi, match[0]);
}
}
You can encapsulate the text that you want to replace with group constructs, and since you're using String.prototype.replace, you can capture the parenthesized group and pass the callback function as the 2nd argument in your .replace function.
Read more about it here
Example:
const textString = "This is ph54321 or ph12345";
const newString1 = textString.replace(/(ph)\d{5}/gi, function (matches, p1) {
return p1 + "appended"; // "This is phappended or phappended"
});
const newString2 = textString.replace(/ph(\d{5})/gi, function (matches, p1) {
return "BIGPH" + p1; // "This is BIGPH54321 or BIGPH12345"
});
console.log({newString1});
console.log({newString2});

Javascript replace a string

I want to change this
[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]
into this
Text
using javascript
I have try this one.
<script>
var str = "[s=/site_menu.xhtml?get-d=4%2027&get-id=315&get-title=DanMachi%20Season%202&get-main=DanMachi]DanMachi Season 2[/s]";
var res = str.replace("[s=", '<a href="');
var ser = res.replace("[/s]", "</a>");
var serr = ser.replace("]", ':admin-hash-amp:">');
document.write(serr);
</script>
You may want to consider simply creating a function that would encapsulate all of this for you, especially if you plan on using in within multiple areas of your application:
function toHyperLink(input){
return input.replace('[s=','<a href="')
.replace(']','">')
.replace('[/s]','</a>');
}
Example
var input = '[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]';
console.log(`Input: ${input}`);
console.log(`Output: ${convertToHyperlink(input)}`);
function convertToHyperlink(input) {
return input.replace('[s=', '').replace('[/s]', '');
}
After you do your convert you should create an element instead of write that out.
var str = "[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]";
var res = str.replace("[s=", '<a href="');
var ser = res.replace("[/s]", "</a>");
var serr = ser.replace("]", '">');
var text = serr.slice(serr.indexOf(">") + 4, serr.indexOf("</a&gt"))
var href = serr.slice(serr.indexOf("href=\"") + 6, serr.indexOf("\"&gt"))
var link = document.createElement("a");
link.text = text;
link.href = href;
document.getElementById("myDIV").appendChild(link);
Try this
var str = "[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]";
var r = str.replace(/\[s=(.*?)\](.*?)(\[\/s\])/gi,"<a href='$1'>$2</a>");
document.write(r);
I guess you may also do like;
var str = "[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]",
res = str.replace(/\[s(.+)\](.+)\[\/s\]/, "<a href$1>$2</a>");
console.log(res);

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

How to handle Querystring in 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 :-)

Categories

Resources