Skip to content

Instantly share code, notes, and snippets.

@nmpeterson
Last active November 16, 2022 20:12
Show Gist options
  • Save nmpeterson/2eb1b58499136e8d6bec958eca06915a to your computer and use it in GitHub Desktop.
Save nmpeterson/2eb1b58499136e8d6bec958eca06915a to your computer and use it in GitHub Desktop.
A function for ArcGIS Arcade to break a string into lines approximately matching a target length.
// Line-break enforcer, for instances where ArcGIS Pro won't automatically
// insert line breaks in long strings (e.g. in composite callouts).
// The targetWidth parameter is a character limit that the function will
// use to break the input str into multiple lines. Individual lines may
// be slightly longer or shorter than the targetWidth, depending on where
// space characters exist that can be replaced with line breaks.
function insertNewLines(str, targetWidth) {
var words = Split(str, " ")
var lines = []
var curLine = ""
if (Count(words) <= 1) { return str } // str does not contain distinct words
for (var i in words) {
var word = words[i]
var wordLength = Count(word) + 1 // Add one to account for the required space character
var curLength = Count(curLine)
if (curLength + wordLength < targetWidth) {
// Add current word to current line if combined length below target
curLine = Concatenate([curLine, word], " ")
} else if (Abs(targetWidth - curLength) < Abs(targetWidth - (curLength + wordLength))) {
// If current line's length is closer to target without new word, begin a new line
Push(lines, curLine)
curLine = word
} else {
// Add new word to current line and then begin a new line
curLine = Concatenate([curLine, word], " ")
Push(lines, curLine)
curLine = ""
}
}
// Push final line if not blank
if (!IsEmpty(curLine)) {
Push(lines, curLine)
}
// Join individual lines with newline character
return Concatenate(lines, TextFormatting.NewLine)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment