如何使用正则表达式进行一些 Javascript 字符串操作

How do I use regex to do some Javascript string manipulation?

本文关键字:Javascript 字符串 操作 何使用 正则表达式      更新时间:2023-09-26

我有一个字符串,它以表行标签<tr>...</tr>开头和结尾。这其中有多个<td>,其形式如下:

<td class="someClass">TextIWant TextI Do NOtWant</td><td><img src='green.png'></td>
<td class="someClass">TextIWant TextI Do NOtWant</td><td><img src='blue.png'></td>

我想做的是查看颜色.png,并在 td 中添加一个类,并修剪 td 中的一些文本。最终输出应如下所示:

<td class="someClass green">TextIWant</td>
<td class="someClass blue">TextIWant</td>

如何使用正则表达式执行此操作?

您可能需要提供有关您需要做什么的更多详细信息,但最好的做法是使用 DOM 解析器,JavaScript 内置了一个非常好的解析器(不支持 IE8-)。

// Select all odd `td` nodes and iterate over them
Array.prototype.forEach.call(document.querySelectorAll("td:nth-child(odd)"),
function (elem) {
    // Get the immediately following sibling (with the img)
    var imgTd = elem.nextSibling;
    // Get the color from the <img>
    elem.className += ' ' + imgTd.querySelector("img").getAttribute("src")
        .replace('.png', '');
    // Remove the sibling
    imgTd.parentNode.removeChild(imgTd);
    // Update the initial elements text to remove the undesired text
    elem.textContent = elem.textContent.replace("TextI Do NOtWant", "");
});

http://jsfiddle.net/e9vrK/

id 使用 jquery 执行此操作,如下所示:

var td;
var img;
var color;
 $('img').each(function(){
   img=$(this);
   td = img.closest('td').prev();
   color = img.attr('src').split('.')[0]
     td.html('the image is '+color+'.png').addClass(color);
 });

演示在这里 http://jsfiddle.net/QHkbe/2