Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

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 :

rust
```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()
}
results start

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.)

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

use urlencoding::encode;

fn main() {
  let encoded = encode("This string will be URL encoded.")
    .into_owned();
  println!("{}", encoded);
}
results start

- The [TODO: Code shorthand span ] call returns a [TODO: Code shorthand span ] . Calling [TODO: Code shorthand span ] is what makes it a [TODO: Code shorthand span ]

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