Next to what you yourself suggested, here is a classic loop approach. As mentioned by someone in the commentary, it is more stable because you do not run the risk of screwing the object and throwing an error, trying to parse it. On the other hand, some questions arise (see below).
, needle . - quoting.
, , . fiddle.
Object.replaceAll = function (entity, needle, replacement, affectsKeys, affectsValues) {
affectsKeys = typeof affectsKeys === "undefined" ? true : affectsKeys;
affectsValues = typeof affectsValues === "undefined" ? true : affectsValues;
var newEntity = {},
regExp = new RegExp( needle, 'g' );
for( var property in entity ) {
if( !entity.hasOwnProperty( property ) ) {
continue;
}
var value = entity[property],
newProperty = property;
if( affectsKeys ) {
newProperty = property.replace( regExp, replacement );
}
if( affectsValues ) {
if( typeof value === "object" ) {
value = Object.replaceAll( value, needle, replacement, affectsKeys, affectsValues );
} else if( typeof value === "string" ) {
value = value.replace( regExp, replacement );
}
}
newEntity[newProperty] = value;
}
return newEntity;
};
, :
var replaced = Object.replaceAll( { fooman: "The dog is fooking" }, "foo", "bar" );
, , . :
// do you expect it to stay undefined or change type and become "undebazed"?
console.log( Object.replaceAll( { x: undefined }, "fin", "baz" ) );
// null or "nalala"?
console.log( Object.replaceAll( { x: null }, "ull", "alala" ) );
// true or false?
console.log( Object.replaceAll( { x: true }, "true", "false" ) );
// true or "foo"?
console.log( Object.replaceAll( { x: true }, "true", "foo" ) );
console.log( Object.replaceAll( { x: 1337 }, "33", "00" ) );
console.log( Object.replaceAll( { x: 1337 }, "33", "foo" ) );
- ( ) .