Search code examples
smalltalkhtml-encode

Escape HTML tags in Smalltalk String


I'm desperately trying to write a very basic method in Smalltalk to escape HTML tags ('<' and '>').

So far, this is what I have come up with:

escapeHtml: str
    |tags newString tmpString|
    newString := String new.
    tags := Dictionary new.
    tags at: '<' put: '&lt;'.
    tags at: '>' put: '&gt;'.
    tags keysAndValuesDo:
    [ :k :v |
        tmpString := str copyReplaceAll: k with: v.
        newString := tmpString
    ].
    ^newString
!

Unfortunately, it appears to only replace the very last item of the tags dictionary. What am I doing wrong? I should probably also point out that I have very little experience with Smalltalk.

The Interpreter of choice is 'syx'.


Solution

  • I think that you wanted to make something like

    newString := str
    

    and then in keysAndValuesDo: block:

    tmpString := newString copyReplaceAll: k with: v.
    

    because right now you are generating a tmpString for each key/value pair with only one key replaced. Than you assign it to the newString. To achieve your goal you should send copyReplaceAll: to the string that was processed on previous iteration. This can be done by sending a message to a newString, but for first iteration to work you should assign a value of an str to it.

    P.S. I also think that this cleaner version should work:

    escapeHtml: str
        |tags newString|
        newString := str copy.
        ...
        tags keysAndValuesDo: [ :k :v | newString replaceAll: k with: v ].
        ^newString