How to escape double quotes in a string?

I’m trying to build an <a> tag element by concatenating strings like so

module Main
  ( formatLinks
  )
  where

import Prelude

import Effect (Effect)
import Effect.Console (logShow)

formatLinks :: Array String -> Array String
formatLinks ss =
  map (\s -> "<a"
  <> " src=\"" <> s <> "\""
  <> "</a>") ss

main :: Effect Unit
main = do
  logShow $ formatLinks ["link1", "link2"]

which produce the following result

["<a src=\"link1\"</a>","<a src=\"link2\"</a>"]

How do I escape double quotes properly or log it without backslash character?

Hi and welcome,

how do you test/run your code? Literally putting this into a fresh spago init project and doing spago run does produce the desired output for me.

Sorry, I corrected the original post to make it runable. I looked at compiled JS code and I think it is a problem with logShow. It has it’s own custom formatting for arrays.

ah ok - yes logShow uses show behind the scene and show for String will escape everything as if you would input it

1 Like

Thank you for the prompt reply. I was able to get desired output with log as you suggested. Here is the solution using joinWith helper function to convert Array String -> String

module Main
  ( formatLinks
  , main
  )
  where

import Prelude

import Data.String (joinWith)
import Effect (Effect)
import Effect.Console (log)

formatLinks :: Array String -> Array String
formatLinks ss =
  map (\s -> "<a"
  <> " src=\"" <> s <> "\""
  <> "</a>") ss

main :: Effect Unit
main = do
  formatLinks ["link1", "link2"] 
    # joinWith "\n"
    # log

Will produce

<a src="link1"</a>
<a src="link2"</a>
1 Like

yes that is a nice solution - I’d personally do formatLink instead and use map with it - and I would throw in fold (here from the 'purescript-arrays` package) to make the concat a bit nicer:

import Data.Array (fold)
import Data.String.Common (joinWith)
import Effect (Effect)
import Effect.Console (log)

formatLink :: String → String
formatLink s =
  fold [ "<a src=\"", s, "\">" ]

main :: Effect Unit
main = do
  log $ joinWith ", " $ map formatLink $ [ "link1", "link2" ]

but that’s probably just personal style

1 Like

Wow that fold is pretty cool! I was looking for a cleaner way to do string concatenation but could not find one.

You can also use triple quotes to avoid having the escape, though it’s not all that useful in this case:

Yeah, I saw that option. Mb that would be useful in conjunction with replace :thinking: