JavaScript — конвертировать предложения в тексте в ссылки

демонстрация

Подробности прокомментированы в демоверсии

{amp}lt;!DOCTYPE html{amp}gt;
{amp}lt;html lang='en'{amp}gt;

{amp}lt;head{amp}gt;
  {amp}lt;meta charset='utf-8'{amp}gt;
  {amp}lt;style{amp}gt;{amp}lt;/style{amp}gt;
{amp}lt;/head{amp}gt;

{amp}lt;body{amp}gt;
  {amp}lt;article{amp}gt;
    {amp}lt;pre{amp}gt;
I am the egg man
They are the egg men
I am the walrus
Goo goo g'joob
{amp}lt;/pre{amp}gt;
  {amp}lt;/article{amp}gt;
  {amp}lt;script{amp}gt;
    /*!
     * Convert a given elements (1st param - selector) text into an {amp}lt;a{amp}gt;nchor tag 
     * that when clicked, will jump to translate.google.com site and translates the
     * text within the {amp}lt;a{amp}gt;nchor to a given language (3rd param - langB).
     **
     * @param  {String} selector  The reference of the element (aka tag) to convert.
     * @param  {String} langA     The original language text is in.
     * @param  {String} langB     The language to which the text will be translated to. 
     **
     * @return {Object}           The new DOM Object/tag.
     */

    /* 
    Pass the selector string of target tag, 
    the current language as a two letter abbreviation,
    and the two letter abbreviation of the language that the text will be translated to
    */
    const transLink = (selector, langA, langB) ={amp}gt; {

      // Reference the target tag
      const tag = document.querySelector(selector);
      
      // Get the text of tag and encode it.
      let encoded = encodeURIComponent(tag.textContent);
      
      // Interpolate values into a template literal of the new URI
      const uri = `https://translate.google.com/?hl=en{amp}amp;op=translate{amp}amp;sl=${langA}{amp}amp;tl=${langB}{amp}amp;text=${encoded}`;
      
      // Interpolate values into a template literal of the new {amp}lt;a{amp}gt;nchor
      const link = `{amp}lt;a href="${uri}" target='_blank'{amp}gt;${decodeURIComponent(encoded)}{amp}lt;/a{amp}gt;`;
      
      // Make a Range Object to facilitate selection of tag content
      let range = document.createRange();
      
      // Select all content within tag
      range.selectNodeContents(tag);
      
      // Delete the content
      range.deleteContents();
      
      // Prepend and render the htmlString "link"
      tag.insertAdjacentHTML('afterbegin', link);
      
      // return tag
      return tag;
    }

    /*
    Find the first {amp}lt;pre{amp}gt; then covert its contents from English text into a link 
    with Spanish text
    */
    console.log(transLink('pre', 'en', 'es'));
  {amp}lt;/script{amp}gt;
{amp}lt;/body{amp}gt;

{amp}lt;/html{amp}gt;

Понравилась статья? Поделиться с друзьями:
JavaScript & TypeScript
Adblock
detector