Forums › Adobe After Effects Expressions › Count number of line breaks?
-
Count number of line breaks?
-
Kevin Dazet
March 9, 2023 at 6:04 pmIs it possible to identify the number of line breaks in a text box?
I have an expression in a range selector that attempts to identify the final character in a line of text using sourceText.length. However, if there are any line breaks in the text, these breaks are added to the total number of characters and the resulting number is higher than the index of the character that I’m trying to target.
I came up with a clunky solution that looks at the total sourceRect height to guess the number of lines and then subtract any resulting number that’s higher than 1 from the total number of characters, but this gave me odd results in some cases.
Is there a cleaner way to accomplish what I’m trying to do? Either by tallying the line breaks or with a better expression to target the actual index of the last character?
-
Yoan Boisjoli
March 9, 2023 at 6:17 pmHi Kevin, Yes, it is possible to identify the number of line breaks in a text box using an expression in After Effects. Here is an expression that you can use to achieve this:
var text = sourceText.value;
var lineBreaks = (text.match(/\n/g)||[]).length;
This expression first retrieves the value of the source text, and then uses the match() function with a regular expression to count the number of line breaks in the text. The ||[] part of the expression ensures that the function returns 0 if no line breaks are found.
-
Kevin Dazet
March 9, 2023 at 6:30 pmThanks, Yoan! I get an error, though. I had to change the first line to
var t = text.sourceText.value
But then I get an error saying “undefined value used in expression(could be an out of range array subscript?)”
Any idea what’s wrong?
-
Dan Ebberts
March 9, 2023 at 7:09 pmYou could try this for the number of characters, not counting the line breaks:
text.sourceText.value.replace(/\r/g,"").length
-
Mamoun Kolovos
March 9, 2023 at 8:44 pmmaybe he’s using paragraph text so there aren’t any real line break characters, just visual breaks created by the box
-
Kevin Dazet
March 9, 2023 at 9:11 pmI think I figured it out. I’m not using paragraph text, but I’ve been using soft returns (old habit). I just need to make sure anyone inputting text is using hard returns.
Thanks, guys!
-
Mamoun Kolovos
March 9, 2023 at 9:35 pmyou can match soft returns with \3 so the modified code would be:
text.sourceText.value.replace(/\r|\3/g,"").length
-
Dan Ebberts
March 9, 2023 at 9:37 pmAh. Try it this way (a trick I learned from Filip):
text.sourceText.value.replace(/[\r\3]/g,"").length
Log in to reply.