untested
Miscellaneous helpersCollection of useful code snippets (helpers) in SSJS (server-side JavaScript).
Table of contents
inArray
Does a value exist in an array.
function inArray(arr, k) {
var out = false;
var len = arr.length;
while(len--) {
if (arr[len] == k) out = true;
}
return out;
}
<script runat="server">
Platform.Load("core", "1");
try {
var fruit = ["Apple", "Kiwi", "Tomato"];
var result = inArray(fruit, "Tomato");
Write(Stringify(result));
} catch(error) {
Write(Stringify(error));
}
function inArray(arr, k) {
var out = false;
var len = arr.length;
while(len--) {
if (arr[len] == k) out = true;
}
return out;
}
</script>
true
capitalizeFirstLetter
Set the first letter of a string of characters as a capital letter.
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
<script runat="server">
Platform.Load("core", "1");
try {
var str = "the quick brown fox jumps over the lazy dog.";
var result = capitalizeFirstLetter(str);
Write(Stringify(result));
} catch(error) {
Write(Stringify(error));
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
</script>
The quick brown fox jumps over the lazy dog.
sanitizeString
Removes extra spaces, carriage returns and line breaks
function sanitizeString(str) {
var no_spaces = String(str).replace(/\s+/g, ' ');
var no_breaks = String(no_spaces).replace(/(\r\n|\n|\r)/gm, '');
return no_breaks;
}
<script runat="server">
Platform.Load("core", "1");
try {
var str = "The quick brown fox\n\r jumps over the lazy dog.\n\r";
var result = sanitizeString(str);
Write(Stringify(result));
} catch(error) {
Write(Stringify(error));
}
function sanitizeString(str) {
var no_spaces = String(str).replace(/\s+/g, ' ');
var no_breaks = String(no_spaces).replace(/(\r\n|\n|\r)/gm, '');
return no_breaks;
}
</script>
The quick brown fox jumps over the lazy dog.
Help me turn coffee into code
This website is provided to you free of charge. However, a lot of time and effort are spent to write, test and mainain the code. Please consider supporting my work by buying me a cup of coffee.