将文本换行到<b>并由<br>使用jquery

Get text wrapped into <b> and separated by <br> using jquery

本文关键字:并由 br 使用 jquery 文本 换行      更新时间:2023-09-26

我从服务中收到html字符串格式的输出,如下所示:

"<html>↵<h1>↵Example : ↵<br>Explanation↵</h1>↵<hr>↵<b>key1 :  ABCD <br>key2 : 2016-10-18-18-38-29<br>Output: /acddfd/example</b>↵</html>↵"

然后我解析html以获得标记<b>,如下所示:

var input="<html>↵<head>↵<h1>↵Example : ↵<br>Explanation↵</h1>↵<hr>↵<b>key1 :  ABCD <br>key2 : 2016-10-18-18-38-29<br>Output: /acddfd/example</b>↵</html>↵";
var parsed= $.parseHTML(input);

然后我发现解析为html标签数组:

<b>key1 :  ABCD <br>Date : 2016-10-18-18-38-29<br>Output: /acddfd/example</b>

现在我需要得到日期的值,以便进一步操作。
谁能帮助我得到的值日期(例如2016-10-18-18-38-29)使用js/jquery?

使用这个正则表达式

var Date= str.match(/('d{4})-('d{2})-('d{2})-('d{2})-('d{2})-('d{2})/g);

您可以使用Node.nextSibling属性来获取元素后的兄弟文本。它返回Date : 2016-10-18-18-38-29,您需要从字符串中删除额外的部分。

使用String.prototype.split()获取:字符后的字符串。

$(parsed).find("br:first")[0].nextSibling.textContent.split(":")[1].trim();

var date = $("b > br:first")[0].nextSibling.textContent.split(":")[1].trim();
console.log(date);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b>key1 :  ABCD <br>Date : 2016-10-18-18-38-29<br>Output: /acddfd/example</b>

var myString = "<b>key1 :  ABCD <br>Date : 2016-10-18-18-38-29<br>Output: /acddfd/example</b>";
//Break string from date
var myDate = myString.substr(myString.indexOf("Date : ")+"Date : ".length);
//Remove string after date
myDate = myDate.substr(0,myDate.indexOf("<br>"));
console.log(myDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

可以使用下面的代码

var input="<html>↵<head>↵<h1>↵Example : ↵<br>Explanation↵</h1>↵<hr>↵<b>key1 :  ABCD <br>key2 : 2016-10-18-18-38-29<br>Output: /acddfd/example</b>↵</html>↵";
var b_text = $(input).find( 'h1' ).text();