Вырезать часть строки и записать в переменную

Рейтинг: 0Ответов: 2Опубликовано: 18.07.2023

Я получаю JSON со значением свойства description, которое включает в себя разметку HTML (img).

{
"description":"<img width="150" height="150" src="https://www.telecom.com/files/2023/07/Rene.jpg" >This Industry Viewpoint was authored by René d’Avezac de Moran, Fugro Singapore Marine There’s no denying that the region is undergoing a technological renaissance." 
}

Подскажите пожалуйста, как я могу достать из description тег img с его атрибутами и оставить только текст? А img записать в переменную.

Ответы

▲ 0

Можно таким образом:

const json = {
"description": "<img width=`150` height=`150` src=`https://www.telecom.com/files/2023/07/Rene.jpg`>This Industry Viewpoint was authored by René d’Avezac de Moran, Fugro Singapore Marine There’s no denying that the region is undergoing a technological renaissance."
};

function getData(element) {
  const split = element.split('>');
  const img = split[0] + '>';
  const text = split[1];
  return {img, text};
}

console.log(getData(json.description));

▲ 0

как я могу достать из description тег img с его атрибутами и оставить только текст? А img записать в переменную.

Предложу такой вариант решения...

// преобразуем JSON в объект
const o = {
  description: '<img width="150" height="150" src="https://www.telecom.com/files/2023/07/Rene.jpg" >This Industry Viewpoint was authored by René d’Avezac de Moran, Fugro Singapore Marine There’s no denying that the region is undergoing a technological renaissance.' 
}
const od = document.createElement('div')
od.insertAdjacentHTML('beforeEnd', o.description)
const txt = od.textContent
const oi = od.querySelector('img')
console.log(txt)
console.log(oi)