KozStrUtils.js

"use strict";

/**
 * @namespace String
 * @author Kozalo <kozalo@yandex.ru>
 * @copyright Kozalo.Ru, 2016
 */


 /**
  * Uses your regular expression to find matches in the string.
  * @memberof String
  * @param {RegExp|string} re Regular expression. Either a RegExp object or a string.
  * @returns {array} An array of objects. Each object has two fields: "string" and "index". The first one contains a matched string, the second one — the index of the first character of this string.
  */
String.prototype.matchAll = function(re) {
	if (!re instanceof RegExp)
		re = RegExp(re);

	let matchedPairs = [];
	
	let currentString = this;
	let removedLength = 0;

	while (true) {
		let index = currentString.search(re);
		if (index == -1) break;
		let matchedString = currentString.match(re)[0];
		let matchedLength = matchedString.length;

		matchedPairs.push({
			string: matchedString,
			index: removedLength + index
		});

		removedLength += index + matchedLength;
		currentString = currentString.substr(index + matchedLength);
	}

	return matchedPairs;
};


/**
 * Shorten the given string to about _length_ symbols.
 * This method finds the closest whole word, chops it off and appends an ellipsis.
 * @memberof String
 * @param {Integer} length
 * @returns {String}
 * @throws KozExceptions.missingArgument, KozExceptions.invalidArgument, or their string equivalents.
 */
String.prototype.shortenTo = function(length) {
	if (KozUtils !== undefined)
		KozUtils.checkParameters(length, "number", "shortenTo", "length");


    let str = this;

    if (str.length > length)
    {
        let newStr = str.substr(0, length);
        if (str[length] !== ' ')
        {
            let index = newStr.lastIndexOf(' ');
            newStr = newStr.substring(0, index);
        }
        str = newStr.replace(/[.,?!;\-:]*$/, '…')
    }

    return str;
};