Strings (funtions)

var
Strings = {}
Strings.EndsWith     = StringEndsWith
Strings.GenerateSalt = StringGenerateSalt
Strings.RandomHex    = StringRandomHex
Strings.StartsWith   = StringStartsWith
Strings.StripUnicode = StringStripUnicode
Strings.Truncate     = StringTruncate

Ends with

Strings.EndsWith( string, suffix )

function StringEndsWith( string, suffix )
{
	var n = string.length;
	var s = suffix.length;
	var i = string.indexOf( suffix );

	return (i == (n - s));
}

Generate Salt

Strings.GenerateSalt

Returns a string of random hex characters that is 64 characters in length.

function StringGenerateSalt()
{
	return Strings.RandomHex( 64 );
}

Random Hex

Strings.RandomHex

Returns a string of random hex characters.

Based on: https:stackoverflow.com/a/27747377

function StringRandomHex( length )
{
	var array = new Uint8Array( length );

	window.crypto.getRandomValues( array );

	return Array.from( array, StringRandomHex.ToHex ).join( '' );
}

StringRandomHex.ToHex
=
function( decimalValue )
{
	return decimalValue.toString( 16 ).padStart( 2, "0" );
}

Starts with

Strings.StartsWith( string, prefix )

function StringStartsWith( string, prefix )
{
    return (0 === string.indexOf( prefix ));
}

Strip unicode

Strings.StripUnicode( string )

function StringStripUnicode( s )
{
	var r = "";
	var l = "";
	var n = s.length;
	
	for ( var i=0; i < n; i++ )
	{
		try {
			if ( s.charCodeAt( i ) <= 255 )
			{
				r += s.charAt( i );
				l += "#";
			}
			else
			{
				l += "U";
			}
		}
		catch (err)
		{}
	}
	
	console.log( l );
	
	return r;
}

Truncate

Strings.Truncate( string, prefix )

function StringTruncate( text, max_length )
{
	if ( text && (text.length > max_length) )
	{
		text = text.substring( 0, max_length - 3 ) + "...";
	}
	return text;
}