Looks like what your trying to do is url encode your special characters just use the functions:
- encodeURIComponent
- encodeURI
depending on whether you are encoding an entire url or just a component. e.g.
encodeURIComponent("as686sa8d6sa8787^%^%$^£$%£$%");
//Output: "as686sa8d6sa8787%5E%25%5E%25%24%5E%C2%A3%24%25%C2%A3%24%25"
Answer from ShaneQful on Stack OverflowLooks like what your trying to do is url encode your special characters just use the functions:
- encodeURIComponent
- encodeURI
depending on whether you are encoding an entire url or just a component. e.g.
encodeURIComponent("as686sa8d6sa8787^%^%$^£$%£$%");
//Output: "as686sa8d6sa8787%5E%25%5E%25%24%5E%C2%A3%24%25%C2%A3%24%25"
Although deprecated, the escape('myString'); method will do the job and cater for both ? and ! symbols
In my nextjs 13 app I am using the generateStaticParams() method. The issue is a lot of the "urls" have special characters. Such as spaces or even question marks lol.
I'm wondering if there's a simple solution or do I need to write a regex?
When I was using nextjs 12 with getStaticPaths I never had any issues for some reason.
An example of the code is
const Page = ({params}) => {
const {slug} = params;
}
Replace all special characters like 'é' in URL with JavaScript - Stack Overflow
jquery - Remove illegal URL characters with JavaScript - Stack Overflow
regex - javascript : how to replace special symbols/characters that will break your query string in your URL - Stack Overflow
Why do we need to replace `:`, `$`, `,`, `+`, `[`, and `]` back
You need to add encoding. Try this,
src = $('#googlemap').attr('src');
src = encodeURI(src);
$('#googlemap').attr('src', src);
It does actually. The replace function return a new string. Store new string into variable and change the src back.
var src;
var newStr;
src = $('#googlemap').attr('src');
newStr = src.replace('ø', '%C3%B8');
console.log(src);
console.log(newStr);
$('#googlemap').attr('src', newStr);
Those characters are called diacritic (more specifically this tiny stroke above the e).
Here's a JS lib https://github.com/superjoe30/diacritics
You need to modify it slightly in order to use it without any module loader.
Just replace exports.remove with sth. like window.removeDiacrits and then
str = removeDiacrits(str);
and it's probably a good idea to wrap the code in a IIFE.
Did you tried the encodeURI
encodeURI - To encode an URL
encodeURIComponent - to encode the query string parameter
If you wish to keep the symbols in the URI, but encode them:
encodedURI = encodeURIComponent(crappyURI);
If you wish to build 'friendly' URIs such as those on blogs:
niceURI = crappyURI.replace(/[^a-zA-Z0-9-_]/g, '');
You could use the encodeURIComponent function which will properly URL encode the value.
The best way to do this is using URL(). Create a new URL using
var myURL = new URL('http://myhome.com');
Then append search parameters like
var myType="Air B&B";
var myID="RestInPeace";
myURL.searchParams.set('type',myType);
myURL.searchParams.set('name',myID);
This will return an object like
hash: ""
host: "myhome.com"
hostname: "myhome.com"
href: "http://myhome.com/?type=Air+B%26B&name=RestInPeace"
origin: "http://myhome.com"
password: ""
pathname: "/"
port: ""
protocol: "http:"
search: "?type=Air+B%26B&name=RestInPeace"
searchParams: URLSearchParams {}
username: ""
So basically it will preserve your query automatically
Since version 1.5 (ECMA-262 3rd edition, December 1999) JavaScript supports the functions encodeURI() and encodeURIComponent() for exactly this job. I have no idea how you two guys could have overseen this.
See also the question Should I use encodeURI or encodeURIComponent for encoding URLs?
You have 3 options:
escape() will not encode: @*/+
encodeURI() will not encode: ~!@#$&*()=:/,;?+'
encodeURIComponent() will not encode: ~!*()'
But in your case, if you want to pass a url into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.
To be safe and ensure that you've escaped all the reserved characters specified in both RFC 1738 and RFC 3986 you should use a combination of encodeURIComponent, escape and a replace for the asterisk('*') like this:
encoded = encodeURIComponent( parm ).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
[Explanation] While RFC 1738: Uniform Resource Locators (URL) specifies that the *, !, ', ( and ) characters may be left unencoded in the URL,
Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.
RFC 3986, pages 12-13, states that these special characters are reserved as sub-delimiters.
reserved = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
The escape() function has been deprecated but can be used to URL encode the exclamation mark, single quote, left parenthesis and right parenthesis. And since there is some ambiguity on whether an asterisk must be encoded in a URL, and it doesn't hurt to encode, it you can explicitly encode is using something like the replace() function call. [Note that the escape() function is being passed as the second parameter to the first replace() function call. As used here, replace calls the escape() function once for each matched special character of !, ', ( or ), and escape merely returns the 'escape sequence' for that character back to replace, which reassembles any escaped characters with the other fragments.]
Also see 'https://stackoverflow.com/questions/6533561/urlencode-the-asterisk-star-character'
Also while some websites have even identified the asterkisk(*) as being a reserved character under RFC3986, they don't include it in their URL component encoding tool.
Unencoded URL parms:
parm1=this is a test of encoding !@#$%^&*()'
parm2=note that * is not encoded
Encoded URL parms:
parm1=this+is+a+test+of+encoding+%21%40%23%24%25%5E%26*%28%29%27
parm2=note+that+*+is+not+encodeds+not+encoded
You can try encodeUri Built-in function, for example
encodeURI('coño funcionó!')
Previous answer is correct. JavaScript has built in functions for fulfilling this kind of tasks.
You can try to investigate these functions in w3schools.com. Here are the links with basic information and live "Try it out" feature:
- encodeURI - takes string with your characters and encodes it into plausible for url style ( encoding spaces and non ANSII chars )
- decodeURI - takes encoded string and decodes it to initial state
Remove quotes in your regex:
function testFunction() {
path='url("https://www.example.com/folder/next/another/myfilename.jpg")';
var file = path.split('/');
console.log('file is: '+file);
file = file[file.length-1];
console.log('file is: '+file);
file=file.replace(/[")(]*/g, '');
console.log('file is: '+file);
return file;
}
testFunction();
In console:
file is: url("https:,,www.example.com,folder,next,another,myfilename.jpg")
file is: myfilename.jpg")
file is: myfilename.jpg
Return value is "myfilename.jpg" now.
Is it what youwhant?
Correct regex to use here would be /[()"]*/g instead of '/[")(]/g'
Thanks for the help, guys.
I found a simple and easy solution:
template = template.replace(/\{\{image_thumb\}\}/g, function(){ return url });
This way the url is kept and the replace works like a charm
Syntax : RegExp['$&']
Description : The lastMatch property is static, it is not a property of an individual regular expression object. Instead, you always use it as RegExp.lastMatch or RegExp['$&'].
So please not that you have $& in your string and you use it in replace function that use regex expresions :
template = template.replace(/\{\{image_thumb\}\}/g, url);
So the $& in your string will be translated to lastMatch property that will print {{image_thumb}} instead of $&, That why you get :
<img class="thumb-img" src="http://s7d3.scene7.com/is/image/LuxotticaRetail/8053672035704_shad_fr?$jpegdefault{{image_thumb}}wid=45">
Simple example :
var url = "http://s7d3.scene7.com/is/image/LuxotticaRetail/8053672035704_shad_fr?$jpegdefault$&wid=45"
var template = '<img class="thumb-img" src="{{image_thumb}}">';
template = template.replace(/\{\{image_thumb\}\}/g, 'some $& text');
console.log(template);
//will return
<img class="thumb-img" src="some {{image_thumb}} text">
So you have to eliminate the expression $& from your url.
Source
Hope this helps.