JavaScript 歷不支援多行字串(ES6 前),開發者常需將 HTML 模板、SQL、長文本轉為 JS 可用格式:
// 手寫極其痛苦
var html = 'row 1' +
'row 2' +
'row 3';
<script type="module">
// 直接支援多行、插值、標籤模板
const template = `
${title}
${content}
`;
</script>
**現代專案請直接使用模板字面量**,無需後端轉換。
若必須支援舊瀏覽器或舊代碼庫,PHP 可提供轉換工具:
<?php
/**
* 多行文本轉 JS 字串連接格式
* @param string $text 多行文本
* @param string $quote 引號類型:'single' | 'double' | 'backtick'
* @param bool $es6 是否輸出 ES6 模板字面量(預設 false 為相容模式)
* @return string
*/
function textToJsString(string $text, string $quote = 'single', bool $es6 = false): string
{
$text = normalizeLineEndings($text);
$lines = explode("\n", $text);
if ($es6) {
// ES6 模板字面量:需轉義反引號、$、{
$escaped = str_replace(['\\', '`', '$', '{'], ['\\\\', '\\`', '\\$', '\\{'], $text);
return "`{$escaped}`";
}
$quoteChar = $quote === 'double' ? '"' : "'";
$escapeMap = [
'\\' => '\\\\',
$quoteChar => '\\' . $quoteChar,
"\n" => '\\n',
"\r" => '\\r',
"\t" => '\\t',
];
$parts = [];
foreach ($lines as $i => $line) {
$escaped = strtr($line, $escapeMap);
if ($i === 0) {
$parts[] = "{$quoteChar}{$escaped}{$quoteChar}";
} else {
$parts[] = " + {$quoteChar}{$escaped}{$quoteChar}";
}
}
return implode("\n", $parts);
}
function normalizeLineEndings(string $text): string
{
return str_replace(["\r\n", "\r"], "\n", $text);
}
// === Web 介面工具頁 ===
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = $_POST['text'] ?? '';
$quote = $_POST['quote'] ?? 'single';
$es6 = isset($_POST['es6']);
$output = textToJsString($input, $quote, $es6);
}
?>
Text to JS String Converter
多行文本 → JS 字串轉換器
結果
= htmlspecialchars($output) ?>
<?php
function textToJsVar(string $varName, string $text, bool $es6 = false, bool $const = true): string
{
$jsString = textToJsString($text, 'single', $es6);
$keyword = $const ? 'const' : 'let';
return "{$keyword} {$varName} = {$jsString};";
}
// 範例
$html = <<
標題
內容區域
現代建構工具已內建處理,無需手動轉換:
<!-- 直接 import .html 或 .txt -->
<script setup>
import template from './template.html?raw'
// template 即為字串
</script>
// resources/js/components/Modal.vue
// webpack.mix.js
mix.webpackConfig({
module: {
rules: [
{ test: /\.html$/, use: 'raw-loader' },
]
}
});
| 專案類型 | 推薦方案 |
|---|---|
| 現代專案 | ES6 模板字面量 + 建構工具 import raw |
| 需支援 IE11 | Babel 轉譯模板字面量,或 PHP 工具產生連接字串 |
| 純 PHP 專案輸出 JS | PHP 函數產生連接字串,配合 json_encode 確保安全 |
| 動態模板需求 | 後端渲染 Blade/Twig,前端僅負責資料綁定 |
隨著 ES6 普及率超過 99%,「PHP 轉 JS 字串」已成為歷史需求。新專案請直接使用模板字面量與建構工具,舊專案可用本文工具過渡升級。