Skip to content

Instantly share code, notes, and snippets.

@mpecka
Created September 20, 2022 10:51
Show Gist options
  • Select an option

  • Save mpecka/13f0cfc780809cfd7a1b6b3f4619ded3 to your computer and use it in GitHub Desktop.

Select an option

Save mpecka/13f0cfc780809cfd7a1b6b3f4619ded3 to your computer and use it in GitHub Desktop.
JS Truncate String Function
function truncateString(str, len, suffix) {
var suffix = suffix || "...";
var len = len || 10;
if (str.length <= len) {
return str;
} else {
return str.slice(0, len - suffix.length) + suffix;
}
}
/* Examples */
truncateString("1234567890abcdefghij1234567890abcdefghij");
truncateString("1234567890abcdefghij1234567890abcdefghij",20);
truncateString("1234567890abcdefghij1234567890abcdefghij",11,"(truncated)");
truncateString("1234567890abcdefghij1234567890abcdefghij",20,"(truncated)");
@mpecka
Copy link
Author

mpecka commented Sep 20, 2022

Useful e.g. for truncating dataLayer string parameters before pushing to Google Analytics 4 (with event-parameter value 100 characters limit - https://support.google.com/analytics/answer/9267744?hl=en).

@mpecka
Copy link
Author

mpecka commented Sep 20, 2022

And this is GTM Custom Javascript variable:

function() {
	var len = 100;
	var suffix = "...";
	var str = "{{YOUR DATALAYER VARIABLE}}";
	
	if (str.length <= len) {
		return str;
	} else {
		return str.slice(0, len - suffix.length) + suffix;
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment