main.js (2509B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2021 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 var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; 25 var format = require( './../../format' ); 26 27 28 // MAIN // 29 30 /** 31 * Returns the part of a string after a specified substring. 32 * 33 * @param {string} str - input string 34 * @param {string} search - search string 35 * @param {integer} [fromIndex=0] - index at which to start the search 36 * @throws {TypeError} first argument must be a string 37 * @throws {TypeError} second argument must be a string 38 * @throws {TypeError} third argument must be an integer 39 * @returns {string} substring 40 * 41 * @example 42 * var out = substringAfter( 'Hello, world!', ', ' ); 43 * // returns 'world!' 44 * 45 * @example 46 * var out = substringAfter( 'beep boop', 'beep' ); 47 * // returns ' boop' 48 * 49 * @example 50 * var out = substringAfter( 'beep boop', 'boop' ); 51 * // returns '' 52 * 53 * @example 54 * var out = substringAfter( 'beep boop', 'xyz' ); 55 * // returns '' 56 * 57 * @example 58 * var out = substringAfter( 'beep boop', 'beep', 5 ); 59 * // returns '' 60 * 61 * @example 62 * var out = substringAfter( 'beep boop beep baz', 'beep', 5 ); 63 * // returns ' baz' 64 */ 65 function substringAfter( str, search, fromIndex ) { 66 var idx; 67 if ( !isString( str ) ) { 68 throw new TypeError( format( 'invalid argument. First argument must be a string. Value: `%s`.', str ) ); 69 } 70 if ( !isString( search ) ) { 71 throw new TypeError( format( 'invalid argument. Second argument must be a string. Value: `%s`.', search ) ); 72 } 73 if ( arguments.length > 2 ) { 74 if ( !isInteger( fromIndex ) ) { 75 throw new TypeError( format( 'invalid argument. Third argument must be an integer. Value: `%s`.', fromIndex ) ); 76 } 77 idx = str.indexOf( search, fromIndex ); 78 } else { 79 idx = str.indexOf( search ); 80 } 81 if ( idx === -1 ) { 82 return ''; 83 } 84 return str.substring( idx+search.length ); 85 } 86 87 88 // EXPORTS // 89 90 module.exports = substringAfter;