time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

trim.js (1768B)


      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 var replace = require( './../../replace' );
     25 var format = require( './../../format' );
     26 
     27 
     28 // VARIABLES //
     29 
     30 // The following regular expression should suffice to polyfill (most?) all environments.
     31 var RE = /^[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*([\S\s]*?)[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/;
     32 
     33 
     34 // MAIN //
     35 
     36 /**
     37 * Trim whitespace characters from beginning and end of a string.
     38 *
     39 * @param {string} str - input string
     40 * @throws {TypeError} must provide a string primitive
     41 * @returns {string} trimmed string
     42 *
     43 * @example
     44 * var out = trim( '   Whitespace   ' );
     45 * // returns 'Whitespace'
     46 *
     47 * @example
     48 * var out = trim( '\t\t\tTabs\t\t\t' );
     49 * // returns 'Tabs'
     50 *
     51 * @example
     52 * var out = trim( '\n\n\nNew Lines\n\n\n' );
     53 * // returns 'New Lines'
     54 */
     55 function trim( str ) {
     56 	if ( !isString( str ) ) {
     57 		throw new TypeError( format( 'invalid argument. Must provide a string. Value: `%s`.', str ) );
     58 	}
     59 	return replace( str, RE, '$1' );
     60 }
     61 
     62 
     63 // EXPORTS //
     64 
     65 module.exports = trim;