JavaScriptでドルに日本円を自動で併記するサンプル

商品A: 10ドル

商品B: $123

<p>商品A: <span data-usd>10ドル</span></p>
<p>商品B: <span data-usd>$123</span></p>
async function fetchFromCsv(sheetId) {
  const url = `https://docs.google.com/spreadsheets/d/${sheetId}/export?format=csv&gid=0`
  const res = await fetch(url)
  if (!res.ok) throw new Error('読み込み失敗!')
  const text = await res.text()
  return text
}

(async () => {
  try {
    const sheetId = '1hk-Fb9vMwslZZ5F9YyqZB5789xIw9GX7503PjgeHRqw'
    const rateString = await fetchFromCsv(sheetId)
    const usdToJpyRate = Number(rateString)
    const priceElements = document.querySelectorAll('[data-usd]')
    priceElements.forEach((element) => {
      const originalText = element.textContent?.trim() ?? ''
      const usdValue = parseFloat(originalText.replace(/[^0-9.]/g, ''))
      const yenValue = Math.round(usdValue * usdToJpyRate)
      const formattedYen = yenValue.toLocaleString('ja-JP')
      element.textContent = `${originalText} (約${formattedYen}円)`
    })
  } catch (error) {
    console.error('ドル円に変換できませんでした。: ', error)
  }
})()

元記事を表示する