diff --git a/src/Text/Pandoc/Writers/HTML.hs b/src/Text/Pandoc/Writers/HTML.hs
index b1161fded..79d9b12e7 100644
--- a/src/Text/Pandoc/Writers/HTML.hs
+++ b/src/Text/Pandoc/Writers/HTML.hs
@@ -1465,13 +1465,15 @@ inlineToHtml opts inline = do
       case writerHTMLMathMethod opts of
            WebTeX url -> do
               let imtag = if html5 then H5.img else H.img
+              let str' = T.strip str
               let s = case t of
                            InlineMath  -> "\\textstyle "
                            DisplayMath -> "\\displaystyle "
               return $ imtag ! A.style "vertical-align:middle"
-                             ! A.src (toValue . (url <>) . urlEncode $ s <> str)
-                             ! A.alt (toValue str)
-                             ! A.title (toValue str)
+                             ! A.src (toValue . (url <>) .
+                                 urlEncode $ s <> str')
+                             ! A.alt (toValue str')
+                             ! A.title (toValue str')
                              ! A.class_ mathClass
            GladTeX ->
               return $
diff --git a/src/Text/Pandoc/Writers/Markdown/Inline.hs b/src/Text/Pandoc/Writers/Markdown/Inline.hs
index 929912f99..1ae7e1847 100644
--- a/src/Text/Pandoc/Writers/Markdown/Inline.hs
+++ b/src/Text/Pandoc/Writers/Markdown/Inline.hs
@@ -485,8 +485,10 @@ inlineToMarkdown opts (Math InlineMath str) = do
   case () of
     _ | variant == Markua -> return $ "`" <> literal str <> "`" <> "$"
       | otherwise -> case writerHTMLMathMethod opts of
-          WebTeX url -> inlineToMarkdown opts
-                          (Image nullAttr [Str str] (url <> urlEncode str, str))
+          WebTeX url ->
+            let str' = T.strip str
+             in inlineToMarkdown opts
+                  (Image nullAttr [Str str'] (url <> urlEncode str', str'))
           _ | isEnabled Ext_tex_math_dollars opts ->
                 return $ "$" <> literal str <> "$"
             | isEnabled Ext_tex_math_single_backslash opts ->
@@ -507,9 +509,11 @@ inlineToMarkdown opts (Math DisplayMath str) = do
         return $ blankline <> attributes <> cr <> literal "```" <> cr
             <> literal str <> cr <> literal "```" <> blankline
       | otherwise -> case writerHTMLMathMethod opts of
-          WebTeX url -> (\x -> blankline <> x <> blankline) `fmap`
-                 inlineToMarkdown opts (Image nullAttr [Str str]
-                        (url <> urlEncode str, str))
+          WebTeX url ->
+            let str' = T.strip str
+             in (\x -> blankline <> x <> blankline) `fmap`
+                 inlineToMarkdown opts (Image nullAttr [Str str']
+                        (url <> urlEncode str', str'))
           _ | isEnabled Ext_tex_math_dollars opts ->
                 return $ "$$" <> literal str <> "$$"
             | isEnabled Ext_tex_math_single_backslash opts ->