<html>
<head>
</head>
<body>
<table>
<tr>
<td colspan="1">
<p class="Hello-7-blue1">Hello Stack Overflow1</p>
</td>
<td rowspan="1" colspan="2">
<p class="Hello-red">Hello Stack Overflow2</p>
<p class="Hello-6-tab-red">defines red color,that class want to
apply
to</p>
</td>
<td rowspan="1" colspan="1">
<p class="Hello-world-6-orange">Hello Stack Overflow3</p>
</td>
</tr>
</table>
<script>
function convertClassName(src) {
return src.replace(/^.*?-/, "");
}
$("table p").each(function() {
$(this).closest("td").addClass(convertClassName(this.className));
});
</script>
</body>
</html>
预期产出:
<td class="blue1">
<p class="Hello-7-blue1">
<td class="red">
<p class="Hello-6-tab-red">
从上面的问题,我想应用
中提到的类(即,p class =“Hello-7-blue1”)应该应用于它最接近的(即td class =“blue1”) )。
而不是Dash“ - ”,如果我使用Underscore“_”然后它的工作,但在我的页面中有Dash。所以请能帮我一个人
答案 0 :(得分:0)
使用split函数代替正则表达式替换你的函数
function convertClassName(src) {
return src.replace(/^.*?-/, "");
}
与
function convertClassName(src) {
//alert(src);
return src.split("-")[src.split("-").length-1];
}
答案 1 :(得分:0)
您的正则表达式应按以下方式更改:
function convertClassName(src) {
return src.replace(/^.*-/, ""); //<-- Note change here
}