2

I am using this script to convert words on a text to links that open on Google Translate, but I'd like to convert sentences, not word by word, sentences separated on pontuation like "?", ",", ".", ";", ";", ":" and so on. How could I do it?

//script

str = document.getElementById('texto-clicavel').innerHTML;
res = str.replace(/\"/g, "'");
document.getElementById('texto-clicavel').innerHTML = res;
// teste=document.getElementById('texto-clicavel').innerHTML = res;
// console.log(teste)

var criarLink = t => `<a target="_blank" onclick="window.open('https://translate.google.com/m/translate?ie=UTF8&sl=pt-BR&tl=en&q=#en/pt/${t}')">${t}</a>`

var criarArrayDeLinks = e => e.textContent.split(' ').filter(i => i !== '' && i !== '\n').map(i => criarLink(i));


function criarLinksEmElementos(pai) {
  const tags = [];

  if (pai.nodeType == 3 && pai.textContent.trim()) { 
    tags.push(...criarArrayDeLinks(e));
  } else {          
    pai.childNodes
       .forEach(
          e => {         
            if (e.nodeType == 3 && e.textContent.trim()) { 
              tags.push(...criarArrayDeLinks(e));
            } else {          
              tags.push(criarLinksEmElementos(e).outerHTML);
            }
        });
  }

  if (tags.length) {    
    pai.innerHTML = tags.join(' ');    
  }

  return pai;  
}

function criarTextoClicavel(seletor) {  
  const div = document.querySelector(seletor);
  criarLinksEmElementos(div);
}

criarTextoClicavel('#texto-clicavel');
Miguel Silva
  • 147
  • 6
  • Which languages are supported? Different languages define written sentence differently. – EnterSB Dec 26 '19 at 04:16
  • @EnterSB I would like English – Miguel Silva Dec 26 '19 at 13:11
  • Basically, you need text processor. That is not something simple. This example is for simple sentences. https://stackoverflow.com/questions/20320719/constructing-regex-pattern-to-match-sentence – EnterSB Dec 26 '19 at 15:01

2 Answers2

1

Objective

Convert a given elements (1st param - selector) text into an <a>nchor tag that when clicked, will jump to translate.google.com site and translates the text within the <a>nchor to a given language (3rd param - langB).

Because of the security policies here on SO, links to Google are blocked. For a fully functional demonstration, review this Fiddle

Demo

Details are commented in demo

<!DOCTYPE html>
<html lang='en'>

<head>
  <meta charset='utf-8'>
  <style></style>
</head>

<body>
  <article>
    <pre>
I am the egg man
They are the egg men
I am the walrus
Goo goo g'joob
</pre>
  </article>
  <script>
    /*!
     * Convert a given elements (1st param - selector) text into an <a>nchor tag 
     * that when clicked, will jump to translate.google.com site and translates the
     * text within the <a>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) => {

      // 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&op=translate&sl=${langA}&tl=${langB}&text=${encoded}`;
      
      // Interpolate values into a template literal of the new <a>nchor
      const link = `<a href="${uri}" target='_blank'>${decodeURIComponent(encoded)}</a>`;
      
      // 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 <pre> then covert its contents from English text into a link 
    with Spanish text
    */
    console.log(transLink('pre', 'en', 'es'));
  </script>
</body>

</html>
Community
  • 1
  • 1
zer00ne
  • 41,936
  • 6
  • 41
  • 68
  • I would like to convert sentence by sentence according pontuation ("?",";","-",":" and so on) above you converted a full tag, but I'd like sentences by sentences from English text. The language option is welcome, but is not important. – Miguel Silva Dec 26 '19 at 14:43
0

This is was I am doing, I am not sure if it is the most correct way, but it is working

str = document.getElementById('texto-clicavel').innerHTML;
res = str.replace(/\"/g, "'");

//ADDED THIS
res = str.replace(/(,)/g, "$1@@")
.replace(/(\.)/g, "$1@@")
.replace(/(\?)/g, "$1@@")
.replace(/(\!)/g, "$1@@")
.replace(/(;)/g, "$1@@")
;
document.getElementById('texto-clicavel').innerHTML = res;

// teste=document.getElementById('texto-clicavel').innerHTML = res;
// console.log(teste)

var criarLink = t => `<a target="_blank" class="link" onclick="countClicksWords();window.open('https://translate.google.com/m/translate?ie=UTF8&sl=pt-BR&tl=en&q=#en/pt/${t}')">${t}</a>`

var criarArrayDeLinks = e => e.textContent.split('@@').filter(i => i !== '' && i !== '\n').map(i => criarLink(i));

...
Miguel Silva
  • 147
  • 6