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

使用正则表达式迁移第一个textarea中的[media=*]至第二个textarea

实现textarea间media格式内容的迁移与移除

需求说明

从class为test_3的文本框中提取所有[media=*]格式的内容,转移到id为test_4的文本框,同时从原文本框删除这些内容。

初始HTML代码

<textarea style="width:400px;height:100px;" class="test_3">The classification of passenger cars as a class of wheeled vehicles, and within this class, in itself is quite conditional: some cars may be "transitional".

[media=https://youtu.be/JArIzszDb6Y]
[media=https://www.youtube.com/watch?v=JArIzszDb6Y]

The classification of passenger cars.
</textarea>

<textarea style="width:400px;height:100px;" id="test_4"></textarea>

实现代码(JavaScript)

// 获取目标元素
const sourceTextarea = document.querySelector('.test_3');
const targetTextarea = document.getElementById('test_4');

// 匹配所有[media=*]格式内容的正则
const mediaPattern = /\[media=[^\]]+\]/g;

// 提取所有匹配项
const mediaEntries = sourceTextarea.value.match(mediaPattern) || [];

// 将提取的内容写入目标textarea
if (mediaEntries.length) {
  targetTextarea.value = mediaEntries.join('\n');
}

// 移除原textarea中的media内容,并清理多余空行
sourceTextarea.value = sourceTextarea.value.replace(mediaPattern, '')
                                          .replace(/\n{2,}/g, '\n\n');

正则说明

  • \[media=[^\]]+\]:精准匹配[media=xxx]格式的内容,其中[^\]]+确保只匹配到闭合的]为止,不会跨条目匹配
  • g修饰符:全局查找所有符合条件的内容

目标效果代码

<textarea style="width:400px;height:100px;" class="test_3">The classification of passenger cars as a class of wheeled vehicles, and within this class, in itself is quite conditional: some cars may be "transitional".


The classification of passenger cars.
</textarea>

<textarea style="width:400px;height:100px;" id="test_4">
[media=https://youtu.be/JArIzszDb6Y]
[media=https://www.youtube.com/watch?v=JArIzszDb6Y]
</textarea>

内容的提问来源于stack exchange,提问作者G-Force53

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:15:40