'How Can we remove the HTML from string and return an object from it
I have a string which looks like
var str = <strong>Result completed.</strong> This has been done by user steve at 2am
Now, from this string I would like to remove the strong as well as , I am trying divide this string in two parts,
{
title: "Result completed.",
desc: "This has been done by user steve at 2am"
}
So , is there any way I can get this result using javascript
Thanks
Solution 1:[1]
You can use split method in javascript
example:
var str = '<strong>Result completed.</strong> This has been done by user steve at 2am';
var arrayStr = str.split('</strong>');
var objectResult={'title':arrayStr[0].replace('<strong>',''), 'desc':arrayStr[1]};
console.log(objectResult);
Solution 2:[2]
You can use the code below. Although, it is not the best practice I just wrote what came up in my mind first specific to your case. (the string you write). If there will be more HTML tags in your string the code below won't work properly. It is not perfect but it works fine.
const str = '<strong>Result completed.</strong> This has been done by user steve at 2am';
const htmlRemover = (str) => {
let title = "";
let description = "";
const arr = str.split('');
const endOfOpeningTag = arr.indexOf('>') + 1;
const startingOfClosingTag = str.search(/<\//);
arr.slice(endOfOpeningTag, startingOfClosingTag).forEach((el) => title += el);
const newArr = arr.slice(startingOfClosingTag, arr.length);
const newEndOfOpeningTag = newArr.indexOf('>') + 1;
newArr.slice(newEndOfOpeningTag, newArr.length).forEach((el) => description += el);
return {title: title.trim(), description: description.trim()};
};
console.log(htmlRemover(str));
Solution 3:[3]
HTML Parsing Libraries - JavaScript https://scrapingant.com/blog/html-parsing-libraries-javascript
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Brahim Aimen |
| Solution 2 | |
| Solution 3 | Alex |
