#string #replace #regex #pattern #occurrence #matches #slice

string-replace-all

String replacement utility inspired by JavaScript, allowing pattern-based substitutions with support for both exact matches and regex patterns

3 unstable releases

new 0.2.0 Feb 19, 2025
0.1.1 Feb 17, 2025
0.1.0 Feb 17, 2025

#971 in Web programming

Download history 71/week @ 2025-02-12

71 downloads per month

MIT license

17KB
175 lines

string-replace-all

made-with-rust crates.io Documentation MIT licensed

OS Status
Ubuntu-latest Ubuntu Tests
macOS-latest macOS Tests
Windows-latest Windows Tests

The string-replace-all crate enables JavaScript-style string replacement, returning a new String where all occurrences of a pattern are substituted with a specified replacement. It supports both exact matches and regex-based replacements.

  • The pattern can be either a string slice or a Regex.
  • The replacement is always a string slice.
  • The original input string remains unchanged.

This functionality is inspired by JavaScript’s replaceAll(), with the key difference that only string slices are supported as replacements at this time.

Install

cargo add string-replace-all

Usage

Example 1: Using StringReplaceAll Trait

The StringReplaceAll trait extends String and string slices with a replace_all method, allowing for both exact string and regex-based replacements.

use string_replace_all::StringReplaceAll;

let text = "I think Ruth's dog is cuter than your dog!";
let result = text.replace_all("dog", "monkey");

assert_eq!(result, "I think Ruth's monkey is cuter than your monkey!");
use regex::Regex;
use string_replace_all::StringReplaceAll;

let text = "I think Ruth's dog is cuter than your dog!";
let regex = Regex::new("(?i)Dog").unwrap(); // Case-insensitive regex

let result = text.replace_all(&regex, "ferret");

assert_eq!(result, "I think Ruth's ferret is cuter than your ferret!");

Example 2: Using string_replace_all Function

use string_replace_all::string_replace_all;

let text = "I think Ruth's dog is cuter than your dog!";
let result = string_replace_all(text, "dog", "monkey");

assert_eq!(result, "I think Ruth's monkey is cuter than your monkey!");
use regex::Regex;
use string_replace_all::string_replace_all;

let text = "I think Ruth's dog is cuter than your dog!";
let regex = Regex::new("(?i)Dog").unwrap(); // Case-insensitive regex

let result = string_replace_all(text, &regex, "ferret");

assert_eq!(result, "I think Ruth's ferret is cuter than your ferret!");

Testing

Run tests with:

cargo test

License

MIT License (c) 2025 Jeremy Harris.

Dependencies

~2.1–3MB
~54K SLoC