main.js (2597B)
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 isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; 24 var isString = require( '@stdlib/assert/is-string' ).isPrimitive; 25 var format = require( './../../format' ); 26 27 28 // MAIN // 29 30 /** 31 * Returns the part of a string after the last occurrence of a specified substring. 32 * 33 * @param {string} str - input string 34 * @param {string} search - search value 35 * @param {integer} [fromIndex=str.length] - index of last character to be considered beginning of a match 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 = substringAfterLast( 'beep boop', 'b' ); 43 * // returns 'oop' 44 * 45 * @example 46 * var out = substringAfterLast( 'beep boop', 'o' ); 47 * // returns 'p' 48 * 49 * @example 50 * var out = substringAfterLast( 'Hello World', 'o' ); 51 * // returns 'rld' 52 * 53 * @example 54 * var out = substringAfterLast( 'Hello World', '!' ); 55 * // returns '' 56 * 57 * @example 58 * var out = substringAfterLast( 'Hello World', '' ); 59 * // returns '' 60 * 61 * @example 62 * var out = substringAfterLast( 'beep boop baz', 'p b', 6 ); 63 * // returns 'oop baz' 64 */ 65 function substringAfterLast( 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 a nonnegative integer. Value: `%s`.', fromIndex ) ); 76 } 77 idx = str.lastIndexOf( search, fromIndex ); 78 } else { 79 idx = str.lastIndexOf( 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 = substringAfterLast;