Question

So I have a string, something like "first-second-third-100201". I want to select the last - and replace it with a /.

If I wanted to replace the first instance, I could do something like

<#assign string = "first-second-third-100201 />
${string?replace("-","/","f"}

passing "f" for first as the third parameter. However, Freemarker does not seem to have a similar "last" built-in in order to select the last instance of the dash.

Does anyone have any experience simulating this built-in with regex or have an idea of how to do so? Thanks!

EDIT:

So this is pretty ugly, but its technically working.

<#assign first = "first-second-third-100201" >
<#assign last = first?last_index_of('-')>
<#assign last_replace = first?substring(0, last + 1) />
<#assign permalink_beg = first?substring(0, last) />
<#assign permalink_end = first?replace(last_replace, '/') >
${permalink_beg}${permalink_end}

evaluates to first-second-third/100201

Anyone else have a simpler/more elegant solution?

Was it helpful?

Solution 2

You can use regular expression with a capturing group:

<#assign string="first-second-third-100201" />
${string?replace("-([^-]*)$", "/$1", "r")}

Output is first-second-third/100201.

In the regular expression, the ([^-]*) capture the substring after the last -. In the replacement string, the $1 is replaced by the value of the captured group.

OTHER TIPS

Try this:

${string?replace("-"," ")?word_list?last}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top