В настоящее время я работаю над приложением, которое должно извлечь innerHTML из Body, а затем извлечь текст из него в формате JSON.Этот JSON будет использоваться для перевода, а затем переведенный JSON будет использоваться в качестве входных данных для создания той же разметки HTML, но с переведенным текстом.Ниже приведен фрагмент кода.
Ввод HTML
<section>Hello, <div>This is some text which I need to extract.<a class="link">It can be <strong> complicated.</strong></a></div><span>The extracted text should contain the html tag if it has any html tag in the span,p or a tag</span><p>Please see the <span>desired output below.</span></p>Thanks!</section>';
Перевод JSON-вывода
{
"text1":"Hello, ",
"text2":"This is some text which I need to extract.",
"text3":"It can be <strong> complicated.</strong>",
"text4":"The extracted text should contain the html tag if it
has any html tag in the span,p or a tag",
"text5":"Please see the <span>desired output below.</span>",
"text6":"Thanks!"
}
Перевод JSON-ввода
{
"text1":"Hello,-in spanish ",
"text2":"This is some text which I need to extract.-in spanish",
"text3":"It can be <strong> complicated.-in spanish</strong>",
"text4":"The extracted text should contain the html tag if it
has any html tag in the span,p or a tag-in spanish",
"text5":"Please see the <span>desired output below.-in spanish</span>",
"text6":"Thanks!-in spanish"
}
Перевод HTML-вывода
<section>Hello,-in spanish <div>This is some text which I need to extract.-in spanish<a class="link">It can be <strong> complicated.-in spanish</strong></a></div><span>The extracted text should contain the html tag if it has any html tag in the span,p or a tag-in spanish</span><p>Please see the <span>desired output below.</span></p>Thanks!-in spanish</section>';
Я пробовал различные регулярные выражения, но ниже приведен один из потоков, которые я закончил, но я не могу достичь желаемого результата с этим.
//encode
const bodyHTML = '<a class="test">hello world<strong> this is gonna be hard</strong></a>';
//replace the quotes with escape quotes
const htmlContent = bodyHTML.replace(/"/g, '\\"');
let count = 0;
let translationObj = {};
let newHtml = htmlContent.replace(/\>(.*?)\</g, function(match) {
//remove the special character
match = match.replace(/\>|\</g, '');
count = count + 1;
translationObj[count] = match;
return '>~' + count + '~<';
});
const translationJSON = '{"1":"hello world in spanish","2":" this is gonna be hard in spanish","3":""}';
//decode
let trasnaltedHtml = '';
const translatedObj = JSON.parse(translationJSON)
trasnaltedHtml = newHtml.replace(/\~(.*?)\~/g, function(match) {
//remove the special character
match = match.replace(/\~|\~/g, '');
return translatedObj[match];
});
//replace the escape quotes with quotes
trasnaltedHtml = trasnaltedHtml.replace(/\\"/g, '"');
//console.log()
console.log("bodyHTML", bodyHTML);
console.log('tranlationObj', translationObj);
console.log("translationJSON", translationJSON);
console.log('newHtml', newHtml);
console.log("trasnaltedHtml", trasnaltedHtml);
Я ищу работающее регулярное выражение или любой другой подход в мире JS, который бы дал желаемый результат.Я хочу получить весь текст внутри HTML в форме JSON.Другое условие - не разбивать текст, если у него есть некоторые внутренние html-теги, чтобы мы не теряли контекст предложения, например <p>Click <a>here</a></p>
, его следует рассматривать как один текст "Click <a>here</a>"
.Надеюсь я прояснил все сомнения
Заранее спасибо!