main.js (2008B)
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 isString = require( '@stdlib/assert/is-string' ).isPrimitive; 24 25 26 // VARIABLES // 27 28 var RE_CHARS = /[-\/\\^$*+?.()|[\]{}]/g; // eslint-disable-line no-useless-escape 29 30 31 // MAIN // 32 33 /** 34 * Escapes a regular expression string. 35 * 36 * @param {string} str - regular expression string 37 * @throws {TypeError} first argument must be a string primitive 38 * @returns {string} escaped string 39 * 40 * @example 41 * var str = rescape( '[A-Z]*' ); 42 * // returns '\\[A\\-Z\\]\\*' 43 */ 44 function rescape( str ) { 45 var len; 46 var s; 47 var i; 48 49 if ( !isString( str ) ) { 50 throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' ); 51 } 52 // Check if the string starts with a forward slash... 53 if ( str[ 0 ] === '/' ) { 54 // Find the last forward slash... 55 len = str.length; 56 for ( i = len-1; i >= 0; i-- ) { 57 if ( str[ i ] === '/' ) { 58 break; 59 } 60 } 61 } 62 // If we searched the string to no avail or if the first letter is not `/`, assume that the string is not of the form `/[...]/[guimy]`: 63 if ( i === void 0 || i <= 0 ) { 64 return str.replace( RE_CHARS, '\\$&' ); 65 } 66 // We need to de-construct the string... 67 s = str.substring( 1, i ); 68 69 // Only escape the characters between the `/`: 70 s = s.replace( RE_CHARS, '\\$&' ); 71 72 // Reassemble: 73 str = str[ 0 ] + s + str.substring( i ); 74 75 return str; 76 } 77 78 79 // EXPORTS // 80 81 module.exports = rescape;