2014-07-07 31 views
0

我想修剪html文件中的“description”变量以使用javascript去除价格。在html文件中使用JavaScript截断变量

一个典型的描述应该是“帽子,红色 - $ 5.99”在所有情况下,价格 - 也就是“$”之后的所有内容都不应该显示。

下面是HTML代码如下所示:

<tr class="font1"> 
     <td valign="top" align="left" width="15%">[id]</td> 
     <td valign="top" align="left" width="53%">[description] 
</tr> 

该解决方案(How to trim a string after a specific character in java“)eemed来接近,但我不知道如何将我的文件中实现此代码

谢谢。

+0

所以你想''5.99美元'或'帽子,红色'从帽子,红色 - $ 5.99'?请再次确认。 – Braj

回答

0

既然你想你的字符串在$拆分,可以使用String.split()功能与$作为deliminator。

实施例:

var fullDescription = 'hat, red $5.99'; 
var description = fullDescription.split('$')[0] //Split returns an array of the string divided on either side of the $, so take the first element. 

可变description现在将持有'hat, red '

0

1)“Java”和“JavaScript”是不同的东西。 “分裂”概念仍然是您想要的方式,但语法不同。

2)如果要访问和操作HTML内容,对于要更改的元素使用一个类(对于多个元素可重复)或唯一ID(页面上只有一个)通常是一个好主意。你的HTML目前似乎没有这个,所以唯一的选择是抓住所有的<td>元素,并删除所有的价格。如果这就是你想要的,得分!如果没有,那么你需要考虑为选定的单元格添加一个类或类似的东西。 3)一旦你有办法抓取内容,你可以搜索描述中的“$”,并把它放在一个新的字符串中,然后放入单元格中。

//returns every td element, since you have no classes or ids 
    var allCells = document.getElementsByTagName('td'); 

    //loop through the list of td elements 
    for (var i=0; i < allCells.length; i++) { 

     //get the actual HTML content of the cell 
     var currentCellText = allCells[i].innerHTML; 

     //split the description text at the '$' and replace the table cell contents    
     var newText = currentCellText.split('$')[0]; 
     allCells[i].innerHTML = newText; 

    } 

请注意,这是假定的几件事情:

  • 只有1“$”中介绍
  • ,价格永远是一切你想保持&后后什么都没有您需要
  • 说明相对较短。如果您在“$”之前有1000个单词,则此方法效率不高。