簡體   English   中英

使用 Javascript 從字符串生成 HTML 代碼

[英]HTML code generation from string using Javascript

我正在開發一個 javascript 工具,它將提取字符串、獲取相關字符串並創建 html 標簽。

const string = "Create heading 1 that will have class abc and id xyz";

const elementList = [
{name: 'heading 1', tag: 'h1'},
{name: 'heading 2', tag: 'h2'}
{name: 'paragraph', tag: 'p'},
];

function convertTag(input) {
  return elementList.reduce((acc, a) => {
  const re = new RegExp(a.name,"g");
  return acc.replace(re, a.tag);
  }, input);
}

let initialString = convertTag(string)
//returns create h1 that will have class abc and id xyz
let htmlElement = initialString. split (" ")[1];  // will return h1
let code = `<${htmlElement}> </${htmlElement}>`;

如何包含 class 和 Id? 可能還有其他屬性,如 alt、src 等。是否有任何庫可以獲取 HTML 屬性?

謝謝

運行以下代碼的結果是在控制台中打印abc xy 這個想法是搜索前綴“class”和“id”,然后抓取1個或多個字母數字字符,將它們捆綁在一起並返回它們。 匹配 function 返回一堆東西,包括字符串中的 position。 由於我們只對第一個(唯一)結果感興趣,我們可以從結果中獲取元素 0。 把它當作一個簡單的數組。

半醒的人會注意到這些簡單的正則表達式將允許 number 開始下一個組。 與其抓取 1 個或多個字母數字,我認為更強大的解決方案是抓取 1 個 alpha 和 0 個或更多字母數字。

有人把我放在 Expresso 上,作為一個有用的(免費)工具,可以在桌面上玩正則表達式。

function test1()
{
    const s = 'Create heading 1 that will have class abc and id xy';
    let cl = s.match(/(?<=class )\w+/)[0];
    let id = s.match(/(?<=id )\w+/)[0];
    console.log(cl,id);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM