String replace

3 snippets across 3 stacks - Bash & Linux, JavaScript, Regular Expressions

Also written as replace string

SHBash & Linux

String Operations

SH · Bash Scripting
Syntax
${#string}          # length
${string:offset:length}  # substring
${string/pattern/replacement}
Example
FILEPATH="/opt/app/logs/server.log"
echo "Length: ${#FILEPATH}"
echo "Filename: ${FILEPATH##*/}"
echo "Directory: ${FILEPATH%/*}"
echo "Change ext: ${FILEPATH%.log}.txt"

URL="https://api.example.com"
echo "${URL/#https/http}"
Output
Length: 26
Filename: server.log
Directory: /opt/app/logs
Change ext: /opt/app/logs/server.txt
http://api.example.com

Note ## removes longest prefix match, # removes shortest. %% removes longest suffix, % removes shortest. These are pure Bash operations (no subprocess), so they are much faster than calling sed or basename in a loop.

JSJavaScript

Replacing Text

JS · Strings
Syntax
str.replace(search, replacement)
str.replaceAll(search, replacement)
Example
const template = "Hello {name}, welcome to {place}!";
const filled = template
  .replace("{name}", "Ava")
  .replace("{place}", "Berlin");
console.log(filled);

const csv = "a,b,c,d";
console.log(csv.replaceAll(",", " | "));
Output
"Hello Ava, welcome to Berlin!"
"a | b | c | d"

Note replace() only swaps the first match unless you use a regex with the /g flag. replaceAll() replaces every occurrence.

RXRegular Expressions

JS: replace() / replaceAll()

RX · String Operations with Regex
Syntax
string.replace(/pattern/, replacement)
string.replaceAll(/pattern/g, replacement)
Example
// Backreference in replacement
'John Smith'.replace(/(\w+) (\w+)/, '$2, $1')
// Function replacement
'hello'.replace(/\w/g, c => c.toUpperCase())
Output
"Smith, John"
"HELLO"

Note In the replacement string, $1 $2 refer to captured groups, $& is the full match, $` is before-match, $' is after-match. Use a function for dynamic replacements. replaceAll() requires the g flag on regex arguments.

Frequently asked questions

How does Bash & Linux handle string replace?
This task is covered in 3 stacks on this page: Bash & Linux, JavaScript, Regular Expressions. The "String Operations" snippet in Bash & Linux uses `${#string} # length`.
Which command does the Bash & Linux example use?
The "String Operations" snippet uses `${#string} # length`, from the Bash Scripting section of the Bash & Linux cheat sheet.
Which stacks cover "string replace" on this page?
Bash & Linux, JavaScript, Regular Expressions. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "String Operations": ## removes longest prefix match, # removes shortest. %% removes longest suffix, % removes shortest. These are pure Bash operations (no subprocess), so they are much faster than calling sed or basename in a loop.