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

使用TipTap generateJSON处理含URL字符串未生成链接求助

解决TipTap纯文本转节点时URL未转为链接的问题

问题原因

generateJSON 仅负责将纯文本包装为基础的 Paragraph + Text 节点,没有内置URL识别与转换逻辑,所以无法自动把文本中的URL转为Link节点。

两种解决思路

思路1:手动解析文本构建节点

自己写逻辑分割文本中的普通内容和URL,手动构建符合TipTap规范的节点结构:

import { Document, Text, Link, Paragraph } from '@tiptap/extension';

// 分割文本为普通内容和URL片段
function splitTextAndUrls(text) {
  const urlRegex = /(https?:\/\/[^\s]+)/g;
  const segments = [];
  let lastPos = 0;
  let matchResult;

  while ((matchResult = urlRegex.exec(text)) !== null) {
    // 添加URL前的普通文本
    if (matchResult.index > lastPos) {
      segments.push({ type: 'text', content: text.slice(lastPos, matchResult.index) });
    }
    // 添加URL对应的Link节点
    segments.push({
      type: 'link',
      attrs: { href: matchResult[0] },
      content: [{ type: 'text', content: matchResult[0] }]
    });
    lastPos = matchResult.index + matchResult[0].length;
  }

  // 添加剩余的普通文本
  if (lastPos < text.length) {
    segments.push({ type: 'text', content: text.slice(lastPos) });
  }

  return segments;
}

const targetString = "Hello world https://www.example.com";
const paragraphContent = splitTextAndUrls(targetString);

// 组装成完整的TipTap节点JSON
const finalJson = {
  type: 'document',
  content: [
    {
      type: 'paragraph',
      content: paragraphContent
    }
  ]
};

思路2:利用TipTap Editor的自动链接扩展

借助Autolink扩展,让临时编辑器自动识别URL并转换为Link节点:

import { Editor } from '@tiptap/core';
import { Document, Paragraph, Text, Link } from '@tiptap/extension';
import Autolink from '@tiptap/extension-autolink';

async function convertTextToRichJson(text) {
  // 创建临时编辑器实例
  const editor = new Editor({
    extensions: [Document, Paragraph, Text, Link, Autolink],
    content: ''
  });

  // 插入文本,Autolink会自动处理URL
  await editor.commands.insertContent(text);
  const resultJson = editor.getJSON();

  editor.destroy(); // 清理临时编辑器
  return resultJson;
}

// 使用示例
const targetString = "Hello world https://www.example.com";
convertTextToRichJson(targetString).then(json => {
  console.log(json);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:21:31