How to replace spaces in url with + instead of '%20'? - javascript

I am trying to convert my parameters into a string in order to send an api request.
However, my current function replaces the spaces in the parameters into '%20'. How do I change it to change spaces into +?
Example params:
{name: "joe walsh"}
Current result:
...endpoint?name=joe%20walsh
Wanted result:
...endpoint?name=joe+walsh
Here's my current function
stringifyParams(params: any) {
return queryString
.stringify(params)
.replace(/[^?=&]+=(&|$)/g, '')
.replace(/&$/, '')
}

You can use Regex to replace %20 with +.
Append this to the function:
.replace(/%20/g, '+');

Firs you should decode your url with decodeURIComponent and then replace space with plus symbol
Try this peace of code and please let me know if that was useful for you)
const param = "endpoint?name=joe walsh";
console.log(decodeURIComponent(param.replace(" ","+")));

Related

How do I split a string between / and "+" based on an outgoing link click, when there are colons in the actual URL?

JS Beginner here. I need to return itemName from a URL string, however, there are colons in the URL itself. When I split using ("""), I get an error that this won't work.
I have gotten this far, but I don't know what to change in my function to get the desired result. See the examples below:
Below is the URL:
"https://www.website.com/items/item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2"
Below you can see my code.
if ({{Outgoing link}})
var itemName= {{Click URL}};
return itemName.split("/")[5].split(".")[0];
console.log(extractSliceFromUrl(itemName))
}
This is my expected result:
"item-name-1"
This is the actual result I get:
"item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2"
Would the following work?
It extracts whatever's between the last / and the first "+".
const url = "\"https://www.website.com/items/item-name-1\"+\"?date_1=2022-10-05&date_2=2022-10-07&amount=2\"";
console.log(url.substring(url.lastIndexOf('/') + 1, url.indexOf('"+"')));
I'd split by ? first:
const theURL = "https://www.website.com/items/item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2";
theURL.split("?")[0].split("/")[5].split(".")[0];
With the secondary result, you could just remove the ending using:
'"item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2"'.replace(/("[^"]+?")\+/, '$1')
Explanation of /("[^"]+?")\+/ (RegExp)
(...) catch the pattern (becomes the $1)
[^"] everything not "
+? get the shortest result possible
\+ escape + (+ is a special symbol, this will treat it as plain text)
please is the working code.
let strUrl = "https://www.website.com/items/item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2";
let urlArray = strUrl.split("/");
let itemName = urlArray[4].split("?")[0];
console.log(itemName);

Filter last slash of URL and return the last character

I can get the last character of the last part of the URL by using the split method and pop method such as
.split("/").pop() .
But usually, there is a slash at the end of the URL like so: https://exmaple.com/123/456/
It will return empty because there is simply nothing after the last slash.
How do I get the number '6' that is in the last part of the URL in the best and easy way?
One option would be to just remove the slashes, and return the last character no matter what it is.
Here's a quick example:
const getLastChar = (str) =>
str.replaceAll('/', '').slice(-1);
// Example #1 - Trailing slash
console.log(getLastChar('https://exmaple.com/123/456/'));
// Example #2 - No trailing slash
console.log(getLastChar('https://exmaple.com/123/456'));
If it's based on user input, don't forget to also check that the string is present / defined too :)
Just Remove the last "/" Like this:
let str = "https://example.com/abc/123/";
//if the str has a "/" at the end, remove it
if (str.endsWith("/")) {
str = str.slice(0, -1);
}
// str = "https://example.com/abc/123"
console.log(str);

remove all empty values from url string

I'm trying to remove all empty params from a url string. My url looks like this
http://localhost/wm/frontend/www/?test=&lol=1&boo=2
my code should return
http://localhost/wm/frontend/www/?lol=1&boo=2
but it doesn't instead it returns
http://localhost/wm/frontend/www/?&lol=1&boo=2
This is the regex i'm using replace("/(&?\w+=((?=$)|(?=&)))/g","") i know i could just use replace() strings that match '?&' after the 1st replace, but i would rather edit my regex to do so, so it's in 1 line of code. Any ideas?
here is my jsfiddle
You can use this regex for replacement:
/[^?&=]+=(?:&|$)|&[^?&=]+=(?=&|$)/g
And replace it by:
""
RegEx Demo
Try
/\w+=&|&\w+=$/g,
var url = "http://localhost/wm/frontend/www/?test=&lol=1&boo=2&j=";
document.write(url.replace(/\w+=&|&\w+=$/g, ""))
Just try to invoke native's 'replace', which could be used with a regex in its first argument.
str.replace(regex, replace_str)
Please, see this fiddle to see a running example: http://jsfiddle.net/xvqasgmu/1/
You can for example say:
var s = 'http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=';
s = s.replace(/\w*=\&/g, '');
s = s.replace(/&\w*=$/g, '');
That is, remove a block of letters + = + &. Then, remove & + letters + = at the end of the line (indicated by $).
For your input, it returns:
http://localhost/wm/frontend/www/?lol=1&boo=2
See it in JSFiddle or directly here:
var s = 'http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=';
s = s.replace(/\w*=\&/g, '');
s = s.replace(/&\w*=$/g, '');
document.write(s)
Test
If the input contains blocks in the middle and in the end:
http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=
the code I wrote above returns:
http://localhost/wm/frontend/www/?lol=1&boo=2

Javascript replace url with string

I have a string of url encoded characters.
wondering if there is a javascript function that can replace all the url encoded characters with normal string characters.
i know i can use the replace function, but it only replaces one certain character an not all at once
for example, I am looking for one function that will replace all the url encoded characters in this string:
string urlEncoded = '1%20day%20%40work!%20Where%20are%20you%3F'
and give me this string:
string replaced = '1 day # work! Where are you?'
thanks a lot
Use decodeURIComponent(string) for that purpose.
string urlEncoded = '1%20day%20%40work!%20Where%20are%20you%3F';
string replaced = decodeURIComponent(urlEncoded);
alert(replaced);
More info here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURIComponent
string replaced = decodeURIComponent(urlEncoded);
There is also just decodeURI but this does not cope with "special" characters, such as & ? ! # etc
Use decodeURIComponent(urlEncoded)
You are looking for unescape
var decoded = unescape(urlEncoded);

How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning...
I have this:
var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');
locationArray = locationClean.split(" ");
console.log(location);
console.log(locationClean);
console.log(locationArray);
And here is what I am getting in Firebug:
stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]
So for some reason, the replace is only happening once? Do I need to use Regex instead with "/g" to make it repeat? And if so, how would I specifiy a '/' in Regex? (I understand very little of how to use Regex).
Thanks all.
Use a pattern instead of a string, which you can use with the "global" modifier
locationClean = location.replace(/\//g,' ');
The replace method only replaces the first occurance when you use a string as the first parameter. You have to use a regular expression to replace all occurances:
locationClean = location.replace(/\//g,' ');
(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.)
Still, why are you not just splitting on the '/' character instead?
You could directly split using the / character as the separator:
var loc = location.host + location.pathname, // loc variable used for tesing
locationArray = loc.split("/");
This can be fixed from your javascript.
SYNTAX
stringObject.replace(findstring,newstring)
findstring: Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag.
newstring: Required. Specifies the string to replace the found value from findstring
Here's what ur code shud look like:
locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");
njoi'

Categories

Resources