You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现FreeMarker式的DOM innerHTML替换逻辑?

Replicating FreeMarker String Manipulation in JavaScript

Got it, let's translate that FreeMarker logic into plain JavaScript so you can handle the string manipulation directly in your frontend code instead of server-side. Here's how to do it step by step:

First, let's recap what your FreeMarker code does:

  1. Uses widget.description (falls back to an empty string if it's null/undefined)
  2. Adds target='_blank' to every href= attribute in the content
  3. Replaces all instances of font-size with notUsedValue
  4. Replaces all instances of font-family with notUsedValue
  5. Inserts the modified content into an element's innerHTML

JavaScript Implementation

Here's the equivalent code, with explanations:

// Step 1: Get your description content, handle null/undefined cases
const originalDescription = widget.description || '';

// Step 2-4: Apply the three replacement operations (global replacements)
const processedDescription = originalDescription
  // Add target="_blank" to all href attributes
  .replace(/href=/g, "target='_blank' href=")
  // Replace all font-size references
  .replace(/font-size/g, "notUsedValue")
  // Replace all font-family references
  .replace(/font-family/g, "notUsedValue");

// Step 5: Insert into your target element's innerHTML
document.getElementById('your-target-element-id').innerHTML = processedDescription;

Key Notes:

  • Handling empty values: widget.description || '' ensures we don't get errors if widget.description is null, undefined, or an empty string—this matches FreeMarker's ! operator behavior.
  • Global replacements: Using regular expressions with the g flag (/href=/g) ensures every instance of the string is replaced, just like FreeMarker's ?replace (which replaces all matches by default). Without g, JavaScript's replace() only changes the first occurrence.
  • Quoting: We use double quotes for the replacement string to avoid escaping the single quote in target='_blank'—you could also escape single quotes if you prefer single quotes for the string.

If you need to target a different element (like using a class selector instead of ID), just adjust the element selection part—for example:

document.querySelector('.your-target-class').innerHTML = processedDescription;

内容的提问来源于stack exchange,提问作者Khaled Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:13:01