我有一个具有以下格式的字符串:<strong>FirstName LastName</strong>
如何将其更改为包含第一个元素 firstName 和第二个 lastName 的数组?
我这样做了,但运气不好,它不会产生正确的结果:
var data = [myString.split('<strong>')[1], myString.split('<strong>')[2]]
我怎样才能生产["firstName", "lastName"]
对于具有该格式的任何字符串?
最佳答案
为了解析 HTML,使用最好的 HTML 解析器,DOM 本身!
// create a random element, it doesn't have to be 'strong' (e.g., it could be 'div')
var parser = document.createElement('strong');
// set the innerHTML to your string
parser.innerHTML = "<strong>FirstName LastName</strong>";
// get the text inside the element ("FirstName LastName")
var fullName = parser.textContent;
// split it into an array, separated by the space in between FirstName and LastName
var data = fullName.split(" ");
// voila!
console.log(data);
编辑
正如@RobG 所指出的,您还可以显式使用 DOM parser而不是一个元素的:
var parser = new DOMParser();
var doc = parser.parseFromString("<strong>FirstName LastName</strong>", "text/html");
console.log(doc.body.textContent.split(" "));
然而,这两种方法都非常有效;这一切都取决于偏好。
关于JavaScript 从字符串中获取名字和姓氏作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526152/