如何用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:
- Uses
widget.description(falls back to an empty string if it's null/undefined) - Adds
target='_blank'to everyhref=attribute in the content - Replaces all instances of
font-sizewithnotUsedValue - Replaces all instances of
font-familywithnotUsedValue - 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 ifwidget.descriptionis null, undefined, or an empty string—this matches FreeMarker's!operator behavior. - Global replacements: Using regular expressions with the
gflag (/href=/g) ensures every instance of the string is replaced, just like FreeMarker's?replace(which replaces all matches by default). Withoutg, JavaScript'sreplace()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
相关产品推荐
相关产品推荐

