如何在 JavaScript 中將兩個字串連線在一起,其中第一個字串中有空格?


要連線兩個字串,我們需要使用 “+” 運算子在字串之間留出一些空格,但是當第一個字串本身包含空格時,就不必顯式分配空格。 

在下面的示例中,由於字串“str1”本身包含空格,所以只需連線 而不留空格就足以連線這兩個字串。

示例

線上演示

<html>
<body>
   <script>
      function str(str1, str2) {
         return (str1 + str2);
      }
      document.write(str("tutorix is the best ","e-learning platform"));
   </script>
</body>
</html>

輸出

tutorix is the best e-learning platform

如果第一個字串中不存在空格,那麼我們必須建立空格(“ ”)並連線這兩個字串,如下所示。 

示例

線上演示

<html>
<body>
   <script>
      function str(str1, str2) {
         return (str1 + " " + str2);
      }
      document.write(str("tutorix is the best","e-learning platform"));
   </script>
</body>
</html>

輸出

tutorix is the best e-learning platform

更新於: 2020 年 6 月 29 日

5 千多個

開啟您的職業生涯

完成課程認證

開始
廣告