replace.js (2710B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var rescape = require( '@stdlib/utils/escape-regexp-string' ); 24 var isFunction = require( '@stdlib/assert/is-function' ); 25 var isString = require( '@stdlib/assert/is-string' ).isPrimitive; 26 var isRegExp = require( '@stdlib/assert/is-regexp' ); 27 var format = require( './../../format' ); 28 29 30 // MAIN // 31 32 /** 33 * Replace search occurrences with a replacement string. 34 * 35 * @param {string} str - input string 36 * @param {(string|RegExp)} search - search expression 37 * @param {(string|Function)} newval - replacement value or function 38 * @throws {TypeError} first argument must be a string 39 * @throws {TypeError} second argument argument must be a string or regular expression 40 * @throws {TypeError} third argument must be a string or function 41 * @returns {string} new string containing replacement(s) 42 * 43 * @example 44 * var str = 'beep'; 45 * var out = replace( str, 'e', 'o' ); 46 * // returns 'boop' 47 * 48 * @example 49 * var str = 'Hello World'; 50 * var out = replace( str, /world/i, 'Mr. President' ); 51 * // returns 'Hello Mr. President' 52 * 53 * @example 54 * var capitalize = require( '@stdlib/string/capitalize' ); 55 * 56 * var str = 'Oranges and lemons say the bells of St. Clement\'s'; 57 * 58 * function replacer( match, p1 ) { 59 * return capitalize( p1 ); 60 * } 61 * 62 * var out = replace( str, /([^\s]*)/gi, replacer); 63 * // returns 'Oranges And Lemons Say The Bells Of St. Clement\'s' 64 */ 65 function replace( str, search, newval ) { 66 if ( !isString( str ) ) { 67 throw new TypeError( format( 'invalid argument. First argument must be a string. Value: `%s`.', str ) ); 68 } 69 if ( isString( search ) ) { 70 search = rescape( search ); 71 search = new RegExp( search, 'g' ); 72 } 73 else if ( !isRegExp( search ) ) { 74 throw new TypeError( format( 'invalid argument. Second argument must be a string or regular expression. Value: `%s`.', search ) ); 75 } 76 if ( !isString( newval ) && !isFunction( newval ) ) { 77 throw new TypeError( format( 'invalid argument. Third argument must be a string or replacement function. Value: `%s`.', newval ) ); 78 } 79 return str.replace( search, newval ); 80 } 81 82 83 // EXPORTS // 84 85 module.exports = replace;