Replace the last character or number of a string | Freemarker

Viewed 66

I need to check if the last number of character of a ${string} is equal to 9. The string or numbers that I have to handle with is something 831, 519 or 1351. However I dont know how do do it properly. I tried already something like: ${string?replace((string.length)-1,"9")}

At the end there should be instead of 831 --> 839 or 1351 --> 1359 and so on.

Any sugestions about how I can archive this ?

Oh and by the way. If I use the fuction above this error massage comes up: Script error: You have used ?number on a string-value which is not a number (or is empty or contains spaces). And what I tried also was: code snippet Because the original number is somethink like 831.896.

2 Answers

You could use string slicing to keep all characters except for the last one like this:

<#assign string = "1234">
<#assign string = string[0..<string?length-1] + "9">
${string}

Results in:

1239

Since you want to replace that thing, use ?replace. This replaces the last character with 9, if the last character is a digit that's not already 9:

${s?replace("[0-8]$", '9', 'r')}
Related