JavaScript helper: getMaxLengthString [TypeScript]

Here’s a quick JavaScript helper snippet to return a trimmed string based on the calculated maximum length of a string to fit the width of a parent container element.

Written in TypeScript.

/**
 * Takes a full string and returns a trimmed version to fit within a parent space.
 * @param fullLengthString  The full length string to trim to a parent space.
 * @param font              String representing the font styling of the text (required to calculate text length).
 * @param maxLengthPixels   Max pixel width of the parent space to fit the text into.
 * @param removeExtraChars  The number of extr characters to remove from the trimmed space, if required. (Default: 0)
 */
private getMaxLengthString(fullLengthString: string, font: string, maxLengthPixels: number, removeExtraChars: number = 0): string {
	let maxLengthString: string = "";

	let canvas = document.createElement("canvas");
	let context = canvas.getContext("2d");
	context.font = font;

	for (let i = 0; i < fullLengthString.length; i++) { // Build the string maxLengthString = maxLengthString + fullLengthString.charAt(i); // Test the length of the string let metrics = context.measureText(maxLengthString); if (metrics.width > maxLengthPixels) {
			// Trim the string to a max length.

			// The number of characters to remove.
			let removeChars = 1;   // At this point the length is too long, so remove 1 character to get it under.
			if (removeExtraChars > 0) {
				removeChars = removeChars + removeExtraChars;
			}
			removeChars = removeChars * -1; // To make sure they're sliced from the end.

			// Remove characters from the string.
			maxLengthString = maxLengthString.slice(0, removeChars);

			return maxLengthString;
		}
	}

	// Full string is OK.
	return maxLengthString;
}

JavaScript helper: getTextWidth [TypeScript]

Here’s a quick JavaScript helper snippet to calculate width of a string, based on a supplied font styling.

Written in TypeScript.

Credit goes to https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393

/**
 * Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
 *
 * @param {String} text The text to be rendered.
 * @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
 *
 * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
 */
private getTextWidth(text: string, font: string): number {
	// re-use canvas object for better performance
	let canvas = document.createElement("canvas");
	let context = canvas.getContext("2d");
	context.font = font;
	let metrics = context.measureText(text);

	return metrics.width;
}

JavaScript helper: GetElementInnerWidth [TypeScript]

Here’s a quick JavaScript helper snippet to get the inner width (excluding padding) of an element in the DOM.

Written in TypeScript.

/**
 * Return the calculated inner width of an element.
 * Returns -1 if width is unknown.
 * @param elementID         ID of the element to calculate the width for. Set to "" to use elementClassName
 * @param elementClassName  CSS class name on the element to calcualte the width for. Ignored if elementID is provided.
 */
public static GetElementInnerWidth(elementID: string, elementClassName: string): number {
	let width: number = -1;
	let element: any = null;

	// Get the DOM element to check,
	if (elementID !== "") {
		// Lookup by element ID.
		let elementByID = document.getElementById(elementID);
		if (elementByID !== undefined) {
			element = elementByID;
		}
	} else {
		// Lookup by CSS class name. Use first found node as actual element.
		let elementByClass = document.querySelectorAll("." + elementClassName);
		if (elementByClass !== undefined && elementByClass && elementByClass[0]) {
			element = elementByClass[0];
		}
	}

	if (element !== null) {
		// The outer width of the element
		width = element.clientWidth;

		// Get the calculated padding so we can remove it.
		let paddingLeft = ComponentHelpers.TryParseInt(window.getComputedStyle(element, null).getPropertyValue("padding-left"), 0);
		let paddingRight = ComponentHelpers.TryParseInt(window.getComputedStyle(element, null).getPropertyValue("padding-right"), 0);

		// Innerwidth = outerwidth - padding
		width = width - (paddingLeft + paddingRight);
	}

	return width;
}

JavaScript helper: TryParseInt [TypeScript]

Here’s a quick JavaScript helper snippet to test a string and return a parsed integer value, or a default value if the the parse fails.

Written in TypeScript.

 

/**
 * Try to parase an integer value from a string. Returns the number if successful, otherwise return a default value.
 * @param value The string with an integer to parase.
 * @param defaultValue Default value to return if parsing fails.
 */
public static TryParseInt(value: string, defaultValue: number = 0): number {
	let parsedValue = parseInt(value, 10);

	if (isNaN(parsedValue)) {
		// Failed to parse. Return the default value.
		return defaultValue;
	} else {
		// Return the parsed value.
		return parsedValue;
	}
}

Turn ASCII list of text URLs into HTML list of hyperlinks (with Regex and Notepad++)

I have a plain-text (ASCII) list of URLs, with each URL on a new line, and I need to turn it to a HTML list (<ul>) of actual anchor links (<a>).

For example, I start with:

https://www.site1.com/
https://www.site2.com/
https://www.site3.com/
https://www.siten.com/

And want to end up with:

<ul>
<li><a href="https://www.site1.com/">https://www.site1.com/</a></li>
<li><a href="https://www.site2.com/">https://www.site2.com/</a></li>
<li><a href="https://www.site3.com/">https://www.site3.com/</a></li>
<li><a href="https://www.siten.com/">https://www.siten.com/</a></li>
</ul>

In Notepad++ It’s trivial.

  • Paste your list of links into a new document.
  • Open the “Find” dialogue (Ctrl+F).
  • In the “Search Mode” options select “Regular expression”.
  • For “Find what” enter: ^(.+)$
  • For “Replace with” enter: <li><a href=”\1″>\1</a></li>
  • Select “Replace All”.
  • Then you just have to add the “<ul>” and “</ul>” on the first and last lines (respectively).

That’s it.

And here it is with images:


Image 1: The ASCII list of links.


Image 2: A clearer view of the FInd/Replace interface.


Image 3: The result of “Replace All”.

Don’t forget to add the “<ul>” and “</ul>” on the first and last lines.

(Update – 5 minutes later): I just noticed I can set the transparency of the Find/Replace dialogue, so didn’t need the second image. Oh well…)