home ~ projects ~ socials

URL Encode A String In Rust

There's a create that does the encoding (see below), but most of the time I want a pretty URL. This is what I'm using:

```cargo
[dependencies]
regex = "1.10.4"
```

use regex::Regex;

fn main() {
  let source = "- Some ` 42 --- thing; for URL -";
  let output = string_for_url(&source);
  println!("{}", output);
}

fn string_for_url(source: &str) -> String {
      let re1 = Regex::new(r"\W").unwrap();
      let re2 = Regex::new(r"-+").unwrap();
      let re3 = Regex::new(r"^-").unwrap();
      let re4 = Regex::new(r"-$").unwrap();
      let mut updated = source.to_lowercase();
      updated = re1.replace_all(&updated, "-").to_string();
      updated = re2.replace_all(&updated, "-").to_string();
      updated = re3.replace_all(&updated, "").to_string();
      updated = re4.replace_all(&updated, "").to_string();
      updated.to_string()
}
Output:
some-42-thing-for-url

This is the way to do it with actual encoding. (NOTE: I haven't tested the above to see if there are any characters that get passed that shouldn't go in the URL, but it should just be word characters in which case things should be okay.)

```cargo
[dependencies]
urlencoding = "2.1"
```

use urlencoding::encode;

fn main() {
  let encoded = encode("This string will be URL encoded.")
    .into_owned();
  println!("{}", encoded);
}
Output:
This%20string%20will%20be%20URL%20encoded.

Notes

  • The .encode() call returns a Cow. Calling .into_owned() is what makes it a String

TODO

    Test the output from the regex to make sure no invalid URL characters can make it through

-- end of line --