PHP's preg_replace in TypeScript

Rosetta Stone: python/sub ยท ruby/gsub

How to use

Install via yarn add locutus and import: import { preg_replace } from 'locutus/php/pcre/preg_replace'.

Or with CommonJS: const { preg_replace } = require('locutus/php/pcre/preg_replace')

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
1preg_replace('/xmas/i', 'Christmas', 'It was the night before Xmas.')"It was the night before Christmas."
2preg_replace('/xmas/ig', 'Christmas', 'xMas: It was the night before Xmas.')"Christmas: It was the night before Christmas."
3preg_replace('\/(\\w+) (\\d+), (\\d+)\/i', '$11,$3', 'April 15, 2003')"April1,2003"
4preg_replace('/[^a-zA-Z0-9]+/', '', 'The Development of code . http://www.')"TheDevelopmentofcodehttpwww"
5preg_replace('/[^A-Za-z0-9_\\s]/', '', 'D"usseldorfer H"auptstrasse')"Dusseldorfer Hauptstrasse"

Here's what our current TypeScript equivalent to PHP's preg_replace looks like.

export function preg_replace(pattern: string, replacement: string, string: string): string {
// original by: rony2k6 (https://github.com/rony2k6)
// example 1: preg_replace('/xmas/i', 'Christmas', 'It was the night before Xmas.')
// returns 1: "It was the night before Christmas."
// example 2: preg_replace('/xmas/ig', 'Christmas', 'xMas: It was the night before Xmas.')
// returns 2: "Christmas: It was the night before Christmas."
// example 3: preg_replace('\/(\\w+) (\\d+), (\\d+)\/i', '$11,$3', 'April 15, 2003')
// returns 3: "April1,2003"
// example 4: preg_replace('/[^a-zA-Z0-9]+/', '', 'The Development of code . http://www.')
// returns 4: "TheDevelopmentofcodehttpwww"
// example 5: preg_replace('/[^A-Za-z0-9_\\s]/', '', 'D"usseldorfer H"auptstrasse')
// returns 5: "Dusseldorfer Hauptstrasse"
const delimiter = pattern.charAt(0)
const lastDelimiterIndex = pattern.lastIndexOf(delimiter)
let _flag = pattern.substr(lastDelimiterIndex + 1)
_flag = _flag !== '' ? _flag : 'g'
const _pattern = pattern.substr(1, lastDelimiterIndex - 1)
const regex = new RegExp(_pattern, _flag)
const result = string.replace(regex, replacement)

return result
}

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


« More PHP pcre functions


Star