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, '');
Answer from Delan Azabani on Stack OverflowIf 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.
How to remove special characters from URL in jQuery? - Stack Overflow
javascript - Regexp to remove all special characters in URL - Stack Overflow
asp.net - Avoiding special characters in url in javascript - Stack Overflow
how can i delete special characters in a url with javascript? - Stack Overflow
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;
}
Look into
var sPageUrl = "http://localhost/DoSomething/Index/123#";
var number = sPageUrl.substring(sPageUrl.lastIndexOf('/') + 1).replace(/[^\w\s]/gi, '');
alert(number);
You could use regex to strip all special characters from the string
There are two approaches I would consider for this.
Strip off the
#and everything that follows.var number = sPageUrl.substring(0, sPageUrl.indexOf('#')); alert(number);Split on the
#so you have that information when you want it.var number = sPageUrl.split('#'), url, hash; if (number.length > 1) { url = number[0]; hash = number[1]; } alert(url);
Bonus: Both of these approaches also work well for dealing with QueryStrings.
var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=cr%c3%83%c2%a9er*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=créer*"
var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=cr%C3%A9er*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=créer*"
var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=%C3%A9%C3%A8%C3%A0%C3%A7%C3%B9%C3%A2%C3%AA%C3%AE*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=éèàçùâêî*"
Read more:
MDN decodeURI: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURI
MDN decodeURIComponent: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURIComponent
var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=%C3%80%C3%81%C3%82%C3%A0%C3%A1%C3%A2%C3%88%C3%89%C3%8A%C3%A8%C3%A9%C3%AA%C3%8C%C3%8D%C3%8E%C3%AC%C3%AD%C3%AE%C3%92%C3%93%C3%94%C3%B2%C3%B3%C3%B4%C3%99%C3%9A%C3%9B%C3%B9%C3%BA%C3%BB*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=ÀÁÂàáâÈÉÊèéêÌÍÎìíîÒÓÔòóôÙÚÛùúû*"
If it's not something very generic and you have special characters and phrases that you want to replace, you could map your special characters/phrases to their replacements and then decode the string and replace each of them:
var replacements = {
"créer" : "créer", // this is a phrase
"Ã" : "é",
"Â" : "e",
"©" : ""
};
var url = "http://172.23.113.79/recherche/pages/Results.aspx?k=**cr%c3%83%c2%a9er***";
var decoded = unescape(url); // or decodeURI(url);
for(var key in replacements)
decoded = decoded.replace(key,replacements[key]);
There is an API to remove the percent encoding
let string = "ids=%5B%4566abef1c-4462-4g62-bcc5-5ae10547104c%22,%20%1256efcf8c-6977-430d-b3ec-4ae80547101c%22%5D"
let cleanedString = string.removingPercentEncoding
However if you need to extract the UUIDs you can do it with Regular Expression
func extractUUID(from string : String) -> [String]
{
let pattern = "[0-9a-f]{10}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
let regex = try! NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))
return matches.map { match -> String in
let range = Range(match.range, in: string)!
return String(string[range])
}
}
let uuids = extractUUID(from: "ids=%5B%4566abef1c-4462-4g62-bcc5-5ae10547104c%22,%20%1256efcf8c-6977-430d-b3ec-4ae80547101c%22%5D")
print(uuids)
Note: the g in the first UUID is an invalid character
you can remove unwanted characters by adapting the parameters right before passing it into the parser like:
let adaptedParams = params.reduce(into: String: String) { $0[$1.key] = $1.value.joined(separator: ",") }
var str = "abc's test#s";
str.replace(/[^a-zA-Z]/g, "");
use this method. It will remove all the special characters.
You can use str.replace(/[^a-zA-Z ]/g, "") to filter string characters other than special charactes. But this will leave empty spaces so you can further add
.replace( / +/g, ' ' ) to just get one space if there is more than one
var str = "₳This ฿ was ¢ ₡ a dummy ¢ ₢ ₵ ₫ € £ text£ ₤ ₣ ƒin string ₲ ₭ ₥ ₦ ₱ $ $ ₮ ₩ ₩ ¥ ¥ ₴ ¤ ₰containing ៛ ₪ ₯ ₠ ₧ ₨ may௹ ﷼ ㍐ ৲special ৳ ₹ characters"
console.log(str.replace(/[^a-zA-Z ]/g, "").replace( / +/g, ' ' ))
Add the . literal as well then, \.:
var fileName = "I am a file name + two.doc";
fileName.replace(/[^a-zA-Z0-9-_\.]/g, ''); // 'Iamafilenametwo.doc'
It's worth pointing out that the . character in a regular expression will match any single character except the newline character. Therefore you needed to escape the character in order for it to match the literal character, \.
Also, \w is equivilant to [A-Za-z0-9_], therefore you could shorten your expression to:
/[^\w.]/g
And as hwnd points out, if you don't want to allow other dot characters inside the filename, you can use subtraction:
.replace(/(?!\.[^.]+$)\.|[^\w.]+/g, '')
For Windows filenames, I believe a simplified version of the .replace should be
.replace(/[\\/:"*?<>|]/g, '')

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
The first answer in this SO thread contains the code you need to do this.
And what about:
<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>
From: http://php.net/manual/en/function.urlencode.php
Novice user here. I can't figure out how to remove characters like :;/|&$. From a text string to make it url friendly? Help?