2016-08-14 112 views
0

我有字符串,看起來像這樣如何從JavaScript的最後一行刪除某些字符串?

<a href="http://www.page.com/01"><img src="http://www.domain.com/test.jpg" alt=""/></a><!--nextpage--> 
<a href="http://www.page.com/02"><img src="http://www.domain.com/test.jpg" alt=""/></a><!--nextpage--> 
<a href="http://www.page.com/03"><img src="http://www.domain.com/test.jpg" alt=""/></a><!--nextpage--> 

我想要做的是去除僅在最後一行<a href="http://www.page.com/03"></a><!--nextpage-->!所以最終的輸出應該是這樣的:

<a href="http://www.page.com/01"><img src="http://www.domain.com/test.jpg" alt=""/></a><!--nextpage--> 
<a href="http://www.page.com/02"><img src="http://www.domain.com/test.jpg" alt=""/></a><!--nextpage--> 
<img src="http://www.domain.com/test.jpg" alt=""/> 

這是我做的,到目前爲止

var str = '<a href="page.com/01"><img src="domain.com/test.jpg" alt=""/></a><!--nextpage-->\n<a href="page.com/02"><img src="domain.com/test.jpg" alt=""/></a><!--nextpage-->\n<a href="page.com/03"><img src="domain.com/test.jpg" alt=""/></a><!--nextpage-->\n'; 
 
str = str.slice(0, -20); 
 
alert(str)

我設法在最後一行刪除</a><!--nextpage-->。現在我只是不知道如何刪除最後一行的<a href="page.com/03">。請注意,字符串將始終具有不同數量的行和網址

+1

解析HTML到DOM並執行DOM操作。 –

+1

不要將HTML作爲字符串操作。 – 2016-08-14 05:09:52

回答

-1

如果你想單獨做到這一點,而不是DOM操作使用Javascript,這裏是一些代碼witht他幫助的正則表達式

var str = '<a href="page.com/01"><img src="domain.com/test.jpg" alt=""/></a><!--nextpage-->\n<a href="page.com/02"><img src="domain.com/test.jpg" alt=""/></a><!--nextpage-->\n<a href="page.com/03"><img src="domain.com/test.jpg" alt=""/></a><!--nextpage-->\n'; 
var res = str.split("<!--nextpage-->\n"); 
var newString = res[res.length-2].replace(/<a href=\"([\w\.\/]*)\">/,""); 
newString = newString.replace("</a>",""); 
alert(newString) 

這裏是實現提琴相同 https://jsfiddle.net/BoyWithSilverWings/g8bavgtc/

+0

它不給我想要的結果 – TravelWhere

+0

我可以看到它只輸出最後一行。那麼所有其他線條消失的地方呢? – TravelWhere

+0

它被保存爲一個數組。你現在可以看到完整的輸出。 –

2

生成一個包含內容的dom元素,並完成剩餘的操作。

var str = '<a href="http://www.page.com/01"><img src="http://www.domain.com/test.jpg" alt=""/></a><!--nextpage--><a href="http://www.page.com/02"><img src="http://www.domain.com/test.jpg" alt=""/></a><!--nextpage--><a href="http://www.page.com/03"><img src="http://www.domain.com/test.jpg" alt=""/></a><!--nextpage-->'; 
 

 
// create a div eleemnt 
 
var ele = document.createElement('div'); 
 
// set the html content as string 
 
ele.innerHTML = str; 
 
// remove the last child node which is the comment 
 
ele.lastChild.remove(); 
 
// get the last child node currently which is the `a` tag 
 
var a = ele.lastChild; 
 
// replace the `a` tag with its children 
 
// this only works if single child is inside the a tag 
 
// otherwise you need to get all children and 
 
// append child using appendChild method 
 
// after appending all just remove the `a` tag 
 
ele.replaceChild(a.firstChild, a); 
 
// get the updated html content 
 
console.log(ele.innerHTML);

相關問題