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.