使用正则表达式迁移第一个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
相关产品推荐
相关产品推荐

