如何使用正则表达式进行一些 Javascript 字符串操作
How do I use regex to do some Javascript string manipulation?
我有一个字符串,它以表行标签<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
相关文章:
- 可变大小的JavaScript字符串如何成为基元类型
- 如何将angularjs中的javascript字符串输出为循环数组
- 如何使用gump任务将html转换为javascript字符串
- 替换变量时,JavaScript字符串replace()不起作用
- 如何替换JavaScript字符串中除字母和数字之外的所有内容(空格/符号)
- 如何从django中的url解析javascript字符串
- 拆分javascript字符串以获得所需的值
- 使用Bootstrap'在Javascript字符串中的popover插件
- 如何替换javascript字符串中的前三个连字符
- 将JavaScript字符串转换为整数
- jquery/javascript字符串中的撇号
- 正在对java中的javascript字符串进行转义
- 如何在Javascript字符串中添加vaule
- Javascript:字符串中有效的基于数组的替换
- 具有负值的Javascript字符串.slice()
- javascript字符串替换$1(如果它是某个值)
- 将子函数的JavaScript字符串转换为实际函数
- JavaScript字符串中的换行符也保存为.txt
- 将Javascript字符串var传递给HTML href标记
- JavaScript 字符串字母和数字检查