Skip to content

Instantly share code, notes, and snippets.

@irmmr
Last active September 20, 2021 05:48
Show Gist options
  • Save irmmr/274c50f96a5924b6b161f055a3129551 to your computer and use it in GitHub Desktop.
Save irmmr/274c50f96a5924b6b161f055a3129551 to your computer and use it in GitHub Desktop.
The "str_replace" function, same as php for javascript
/**
* Replace all occurrences of the search string with the replacement string.
* @param {array|string} search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
* @param {array|string} replace The replacement value that replaces found search values. An array may be used to designate multiple replacements.
* @param {array|string} subject The string or array being searched and replaced on, otherwise known as the haystack. If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.
* @param {object|null} count If passed, this will be set to the number of replacements performed.
* @returns {array|string} This function returns a string or an array with the replaced values.
*/
function str_replace(search, replace, subject, count = null) {
if ('' === subject) return ''
// classify the subject
if (typeof subject === 'string') subject = [subject]
if (!Array.isArray(subject) || 0 === subject.length) return ''
subject = subject.filter(i => i !== '')
// convert the form of search, replace into an array
if (typeof search === 'string') search = [search]
if (typeof replace === 'string') replace = [replace]
// check for replace, subject types
if (!Array.isArray(search) || !Array.isArray(replace) ||
search.length === 0 || replace.length === 0) return subject
// define custom data and variables
let fetch = Array.call(),
counter = 0
// replace for every subject
for (let sub in subject) {
if (!subject.hasOwnProperty(sub)) continue
let data = subject[sub]
// check every search value for replace it
for (let i in search) {
if (!search.hasOwnProperty(i)) continue
// get the right index to replace
let needle = replace.hasOwnProperty(i) ? replace[i] : replace.slice(-1)[0],
format = new RegExp(search[i].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g')
if (typeof needle === 'undefined') continue
// add count of replacement
if (null !== count) {
counter += (data.match(format) || []).length
}
// placement of all items and texts
data = data.replace(format, needle)
}
// push data to fetch array :)
fetch.push(data)
}
// apply count by reference
if (null !== count && typeof count === 'object') {
count['count'] = counter
}
// return the fetched data
return fetch.length === 1 ? fetch[0] : fetch
}
@irmmr
Copy link
Author

irmmr commented Sep 16, 2021

Examples:

/*
 * see https://www.php.net/manual/en/function.str-replace.php
 * Some examples for str_replace using javascript
 */

// Provides: <body text='black'>
let bodytag = str_replace("%body%", "black", "<body text='%body%'>");

// Provides: Hll Wrld f PHP
let vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
let onlyconsonants = str_replace(vowels, "", "Hello World of PHP");

// Provides: You should eat pizza, beer, and ice cream every day
let phrase  = "You should eat fruits, vegetables, and fiber every day.";
let healthy = ["fruits", "vegetables", "fiber"];
let yummy   = ["pizza", "beer", "ice cream"];

let newphrase = str_replace(healthy, yummy, phrase);

// Provides: 2
let obj = Object.call()
let str = str_replace("ll", "", "good golly miss molly!", obj);
console.log(obj.count);

test in jsfiddle

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment