Swift's String.replacingOccurrences in TypeScript

How to use

Install via yarn add locutus and import: import { replacingOccurrences } from 'locutus/swift/String/replacingOccurrences'.

Or with CommonJS: const { replacingOccurrences } = require('locutus/swift/String/replacingOccurrences')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1replacingOccurrences('hello world', 'l', 'L')'heLLo worLd'
2replacingOccurrences('Swift swift SWIFT', 'swift', 'ts', true)'ts ts ts'
3replacingOccurrences('abcabc', 'ab', '#')'#c#c'

Notes

  • Replaces every occurrence of target in str, similar to Swift replacingOccurrences(of:with:options:).

Here's what our current TypeScript equivalent to Swift's String.replacingOccurrences looks like.

const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

export function replacingOccurrences(
str: string,
target: string,
replacement: string,
caseInsensitive: boolean = false,
): string {
// discuss at: https://locutus.io/swift/String/replacingOccurrences/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Replaces every occurrence of target in str, similar to Swift replacingOccurrences(of:with:options:).
// example 1: replacingOccurrences('hello world', 'l', 'L')
// returns 1: 'heLLo worLd'
// example 2: replacingOccurrences('Swift swift SWIFT', 'swift', 'ts', true)
// returns 2: 'ts ts ts'
// example 3: replacingOccurrences('abcabc', 'ab', '#')
// returns 3: '#c#c'

const source = String(str)
const needle = String(target)
const nextValue = String(replacement)

if (needle === '') {
return source
}

if (caseInsensitive) {
return source.replace(new RegExp(escapeRegExp(needle), 'gi'), nextValue)
}

return source.split(needle).join(nextValue)
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 2 Swift functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

  • Get inspiration from the Swift documentation.
  • Click "New file" in the appropriate folder on GitHub. This will fork the project to your account, directly add the file to it, and send a Pull Request to us.

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.


« More Swift String functions


Star