Javascript return text to html

How to convert a string to HTML in JavaScript

While working with web pages, we often need to convert a string to HTML markup. In this article, you’re going to learn how to convert a piece of text or string to an actual HTML element with JavaScript with examples.

Now, how can we convert this? We’re going to use the DOMParser web API to solve the problem.

What is DOMParser :

The DOMParser interface has the ability to transform XML or HTML source code from a string into a DOM Document. It is a tree-based architecture. Let’s use that.

let ConvertStringToHTML = function (str) < let parser = new DOMParser(); let doc = parser.parseFromString(str, 'text/html'); return doc.body; >;

In this code, we have created a function expression and defined a function inside of it. The function simply takes a parameter, so that we can pass our declared string which is ‘ourString’. Then we have created an instance of the DOMParser interface and from the object, we called the built-in method parseFromString() .

Читайте также:  and

What is parseFromString():

The parseFromString() method of the DOMParser interface converts a string which contains HTML and returns as an HTMLDocument.

The parseFromString() the method takes two parameters. The first one is the string we pass and the second one is the type. In our case, we want to convert to an HTML document, so our type is ‘text/html’. Now, if pass our declared string and log this to our console-

console.log(ConvertStringToHTML(ourString));

You can see that the HTML string is converted to an HTML element as a DOM node. Now, you can use the methods of DOM nodes like appendChild() to use the result. The DOMParser also can convert a string to an XML document. We just have to use a different type like ‘text/xml’. So, in this article, you learned how to convert a string to HTML with Javascript. I hope this example will help you. Thank you.

Источник

Convert Text to HTML using Javascript

In one of our previous post, I have explained how to convert word document into HTML using Javascript, in this article,we will be using Javascript to convert plain text into HTML element.

String to HTML using Javascript

You can simply convert html string into HTML data for user, by providing contents to div.innerHTML in Javascript but it is better to use DOMParser for better output.

So, we can convert string into HTML using these simple steps:

  1. Grab plain text
  2. Check if browser support DOMParser, if yes, convert text into HTML else use fallback
  3. Append Converted HTML into Body.

Here is the Complete Javascript code to do this:

var support = (function () < if (!window.DOMParser) return false; var parser = new DOMParser(); try < parser.parseFromString('x', 'text/html'); >catch(err) < return false; >return true; >)(); var textToHTML= function (str) < // check for DOMParser support if (support) < var parser = new DOMParser(); var doc = parser.parseFromString(str, 'text/html'); return doc.body.innerHTML; >// Otherwise, create div and append HTML var dom = document.createElement('div'); dom.innerHTML = str; return dom; >; document.getElementById("divMain").innerHTML= textToHTML('

Hello

Your HTML Contents are visible now

');

Here is the working fiddle

Convert Plain text into HTML Using jQuery

When using jQuery, you can directly using it’s inbuilt function .html() , here is the custom function

Here is the complete sample HTML

$.fn.toHtml=function() < return $(this).html($(this).text()) >$('.go').click(function()< $('#div').toHtml() >); 

Источник

How to Convert a String to HTML using JavaScript

How to Convert a String to HTML using JavaScript

JavaScript has many built-in APIs and methods that give you control over the HTML on the page.

One of the most useful ways to control the HTML is by converting a string to HTML.

From there, you can use the HTML to append to the DOM, or use it to replace the current page.

In this post, we’ll learn how to convert a string to HTML using JavaScript.

How to convert a String to HTML using JavaScript

To learn how to convert a string to HTML, first let’s define the string of HTML:

 

Convert a String to HTML

Learn how to convert a string to HTML using JavaScript.

`;

Now, we can make use of the built-in DOMParser API to convert the string to HTML.

We already have the string of HTML, so we just need to pass in the type of content to parse, which is text/html :

 

Convert a String to HTML

Learn how to convert a string to HTML using JavaScript.

`; const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html');

From here, we can just take the html and get the body:

 

Convert a String to HTML

Learn how to convert a string to HTML using JavaScript.

`; const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html'); const body = html.body; console.log(body);
 

Convert a String to HTML

Learn how to convert a string to HTML using JavaScript.

We can take the above code and turn it into a reusable function:

 

Convert a String to HTML

Learn how to convert a string to HTML using JavaScript.

`; const convertStringToHTML = htmlString => < const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html'); return html.body; >const body = convertStringToHTML(htmlString); console.log(body);

If we want, we can take this body and append it to the DOM:

In this post, we learned how to convert a string to HTML using JavaScript.

Simply use the built-in DOMParser class and call the parseFromString() method to convert your string into HTML.

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

Give feedback on this page , tweet at us, or join our Discord !

Источник

Convert String to HTML in JavaScript

Convert String to HTML in JavaScript

  1. Use innerHTML Property to Convert String to HTML Object
  2. Use DOMParser() Interface to Convert String to HTML Object
  3. Use jQuery to Ensure the Type of the String Passed in HTML

In JavaScript, some specific convention makes the overall developing history one step ahead to be integrated. Likewise, one of the non-static ways of addressing a string (in the form of an HTML element donating pattern) and later passing it to the HTML body as a unique piece of object.

This makes the interface dynamic and can solve many issues that would have been tough to call otherwise.

The code examples in the following content will demonstrate how to implement this conversion. Firstly, we will pass the string with the innerHTML property.

In the next example, we will use the DOM parse method. This convention is not encouraged mostly, as it has issues with acceptance to many browsers.

In the final section, we will examine if the string we passed was an HTML object or just strings. Let’s dive in!

Use innerHTML Property to Convert String to HTML Object

Here, we will have a function stringToHTML that will take the raw string as its parameter. After that, we will create a div , and we wish to pass the string given inside that.

We could also pass it to the HTML body instead, but to be neat, we expect a div element.

Next, the newly created div will be associated with an instance dom (supposedly). So, for dom , we will set the innerHTML property and then pass the string.

The return will be the dom instance for the function stringToHTML we created. Let’s check the code lines.

 html lang="en"> head>  meta charset="UTF-8">  meta http-equiv="X-UA-Compatible" content="IE=edge">  meta name="viewport" content="width=device-width, initial-scale=1.0">  title>Documenttitle>  head> body>  script src="abc.js">script>  body>  html> 
var stringToHTML = function (str)   var dom = document.createElement('div');  dom.innerHTML = str;  return dom;  >; console.log(stringToHTML('

Hello world!

How are you today?

'
));

Use innerHTML Property to Convert String to HTML Object

Use DOMParser() Interface to Convert String to HTML Object

The DOMParser() is often ignored or can be used along with conditions. If the prior way of handling the issues gets obliterated, then this segment of code might fire to back up the process.

So here, we will take an instance of the DOMParser() interface, and the instance will be triggered by parseFromString() . The parameters will be the string and the type in HTML it is supposed to represent.

We will then pass the instance doc to the HTML body.

 html lang="en"> head>  meta charset="UTF-8">  meta http-equiv="X-UA-Compatible" content="IE=edge">  meta name="viewport" content="width=device-width, initial-scale=1.0">  title>Documenttitle>  head> body>  script src="2.js">script>  body>  html> 
var stringToHTML = function (str)   var parser = new DOMParser();  var doc = parser.parseFromString(str, 'text/html');  return doc.body; >; console.log(stringToHTML('

Hello world!

I am fine Thank you! ^_^

'
));

Use DOMParser() Interface to Convert String to HTML Object

Use jQuery to Ensure the Type of the String Passed in HTML

In this section, we will determine the overall task. We will check if the HTML object was made, the type, etc.

If we can use jQuery to pass a string, it goes to HTML in an object form. Though the content hasn’t been previewed, it has created its space in the HTML body (not permanent).

So, let’s jump to the code block.

 html lang="en"> head>  meta charset="UTF-8">  meta http-equiv="X-UA-Compatible" content="IE=edge">  meta name="viewport" content="width=device-width, initial-scale=1.0">  title>Documenttitle>  head> body>  script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous">script>  script src="3.js">script>  script>  var stringToHTML = function (str)   var d = $(str);  return d;  >  console.log(stringToHTML('

Hello world!

How are you today?

'
));
script>
body> html>

Use jQuery to Ensure the Type of the String Passed in HTML

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

Related Article — JavaScript String

Copyright © 2023. All right reserved

Источник

JavaScript | Как преобразовать строку в HTML-элемент?

Рассмотрен случай преобразования готовой разметки HTML, которая лежит в JavaScript в виде строки.

ТВОЯ_СТРОКА — нужно указать свою строку

ТВОЙ_ЭЛЕМЕНТ — нужно указать HTML-элемент, который получается из строки (тот который задумывался изначально)

Пример создания HTML-элемента из строки - JavaScript

[0] — это значение опционально, если нужно получить какой-либо один элемент из коллекции элементов. Работает целочисленный индекс как у массивов.

Видео инструкция

В этом видео приводится пример преобразования подготовленной строки в HTML-элемент при помощи JavaScript и стандарта «DOM Parsing and Serialization«. Ввод команд осуществляется в консоль браузера Google Chrome. Результат виден сразу.

Строка до нужной строки. Или как мы пришли к этому вопросу.

Переменная stroka со значением - Скачать фото - JavaScript

var newStrLink = stroka.link("efim360.ru")

Мы получили строку, которая полностью оформлена как HTML-разметка ( ВНИМАНИЕ! Это строковый тип данных JavaScript. Не объект DOM интерфейса Element ):

Метод link прототипа String - JavaScript

Теперь нам нужно преобразовать эту строку в HTML-элемент, чтобы иметь возможность взаимодействовать как с объектом. (Доставать значения атрибутов, например из href-атрибута)

Решение задачи

Мы воспользуемся интерфейсом DOMParser, который описан в документе — DOM Parsing and Serialization — https://www.w3.org/TR/DOM-Parsing/

Сначала мы создаём новый объект конструктора DOMParser. Вызываем конструктор при помощи оператора new . Не передаём никаких параметров в конструктор.

Затем у этого объекта мы обращаемся к единственному методу parseFromString:

new DOMParser().parseFromString()

Функция parseFromString() принимает два параметра:

  1. Нужная нам строка
  2. Один из пяти Mime-типов в строком виде ( «text/html» , «text/xml» , «application/xml» , «application/xhtml+xml» , «image/svg+xml» )

Передаём нужные параметры:

new DOMParser().parseFromString(newStrLink, "text/html") или new DOMParser().parseFromString(newStrLink, "text/xml")

Эта конструкция вернёт нам полноценный документ.

С этого момента у нас есть два пути:

Путь № 1 — Использовать «text/html»

Мы получаем новый документ в переменную newDoc .

var newDoc = new DOMParser().parseFromString(newStrLink, "text/html")

DOMParser() возвращает новый документ, ссылка из строки - JavaScript

Нам не нужен сам документ. Нам нужен элемент ссылки, который появился в этом документе.

Мы положили новый документ в переменную и теперь можем отобрать все элементы-ссылки в этом документе (по сути, мы отловим ИМЕННО НАШУ СТРОКУ, с которой начинали)

var aHColl = newDoc.getElementsByTagName("a")

В переменной aHColl будет находиться коллекция HTML-элементов .

Полноценный объект ссылки - элемента a - JavaScript

Под индексом 0(ноль) будет лежать та самая единственная ссылка, которую из строки мы превратили в объект. У этого объекта будут работать все ключи, которые присущи HTML-элементу .

Мы без проблем сможем обратиться к ключу href и получить его полный путь:

Переменная aHColl - ключ href определён - JavaScript

Мы получили href. Всё работает как надо, а значит мы успешно преобразовали строку в HTML-элемент при помощи JavaScript.

Путь № 2 — Использовать «text/xml»

Вариант с «text/xml» вернёт нам «усечённый» документ (не будет и ):

var newStrObject = new DOMParser().parseFromString(newStrLink, "text/xml")

Усечённый документ с одним элементом - JavaScript

Из него также можно будет получить HTML-коллекцию элементов . НО! ВНИМАНИЕ!

Усечённый объект ссылки - элемента a - JavaScript

. У этого объекта не будет ключа href.

Переменная aXColl - ключ href не определён - JavaScript

Объект коллекции не будет содержать нужного количества ключей для своего уникального HTML-элемента. В результате может пострадать логика обработки таких элементов из строк. Будьте внимательны.

Источник

Оцените статью