Supposons que j'ai le texte suivant:

This is a sample url : http://example.com.
These are some images:
<img src="http://example.com/sample1.png" class="sample-image" />
<img src="http://example.com/sample2.png" class="sample-image" />
Another url http://example2.com

Voici le code regex que j'utilise pour analyser le texte ci-dessus:

const urls = /(\b(https?|ftp):\/\/[A-Z0-9+&@#\/%?=~_|!:,.;-]*[-A-Z0-9+&@#\/%=~_|])/gim;
    const emails = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;

    return function(text) {
        if(text.match(urls)) {
            text = text.replace(urls, "<a href=\"$1\">$1</a>")
        }
        if(text.match(emails)) {
            text = text.replace(emails, "<a href=\"mailto:$1\">$1</a>")
        }

        return text
    }

Le code ci-dessus fait cela à mon texte:

This is a sample url : <a href="http://example.com">http://example.com</a>.
These are some images:
<img src="<a href=" class="sample-image">"http://example.com/sample1.png">"
<img src="<a href=" class="sample-image">"http://example.com/sample2.png">"
Another url <a href="http://example2.com">http://example2.com</a>

Et je désire le résultat suivant:

This is a sample url : <a href="http://example.com">http://example.com</a>.
These are some images:
<img src="http://example.com/sample1.png" class="sample-image" /> <!-- Do not change -->
<img src="http://example.com/sample2.png" class="sample-image" /> <!-- Do not change -->
Another url <a href="http://example2.com">http://example2.com</a>

Comment puis-je obtenir le résultat ci-dessus?

1
Samar Rizvi 14 janv. 2017 à 14:23

2 réponses

Meilleure réponse

Il est toujours préférable d'éviter d'utiliser des regex pour analyser le HTML.

Les balises ouvertes RegEx correspondent aux balises autonomes XHTML

Utiliser des expressions régulières pour analyser HTML: pourquoi pas?


var html = 'This is a sample url : http://example.com These are some images:<img src="http://example.com/sample1.png" class="sample-image" /><img src="http://example.com/sample2.png" class="sample-image" />Another url http://example2.com';

// regex for replacing content
const urls = /(\b(https?|ftp):\/\/[A-Z0-9+&@#\/%?=~_|!:,.;-]*[-A-Z0-9+&@#\/%=~_|])/gim;
const emails = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;

// for replacing the content
function update(text) {
  return text.replace(urls, "<a href=\"$1\">$1</a>").replace(emails, "<a href=\"mailto:$1\">$1</a>");
}

// create a DOM element
var temp = document.createElement('div');
// set the string as your content
temp.innerHTML = html;

console.log(
  // get all child nodes and convert into array
  // for older browser use `[].slice.call()`
  Array.from(temp.childNodes)
  // iterate over the elements to generate the content array
  .map(function(n) {
    // if node is text then update the content and return it
    if (n.nodeType == 3)
      return update(n.textContent);
    // otehrwise return the html content
    else
      return n.outerHTML;
    // join them 
  }).join('')
)

MISE À JOUR: Si vous devez conserver le code HTML échappé, vous devez ajouter une méthode supplémentaire qui génère le code HTML échappé correspondant d'un nœud de texte.

var html = 'This is a sample url : http://example.com These are some images:<img src="http://example.com/sample1.png" class="sample-image" /><img src="http://example.com/sample2.png" class="sample-image" />Another url http://example2.com  hi &lt;a href="#"&gt;Sam&lt;/a&gt;';

// regex for replacing content
const urls = /(\b(https?|ftp):\/\/[A-Z0-9+&@#\/%?=~_|!:,.;-]*[-A-Z0-9+&@#\/%=~_|])/gim;
const emails = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;

// for replacing the content
function update(text) {
  return text.replace(urls, "<a href=\"$1\">$1</a>").replace(emails, "<a href=\"mailto:$1\">$1</a>");
}

// function for generating escaped html content for text node
function getEncodedText(node) {
    // temporary element  
    var temp = document.createElement('div');
    // append the text node
    temp.appendChild(node);
    // get the escaped html content
    return temp.innerHTML
  }
  // create a DOM element
var temp = document.createElement('div');
// set the string as your content
temp.innerHTML = html;

console.log(
  // get all child nodes and convert into array
  // for older browser use `[].slice.call()`
  Array.from(temp.childNodes)
  // iterate over the elements to generate the content array
  .map(function(n) {
    // if node is text then update the escaped html content and return it
    if (n.nodeType == 3)
      return update(getEncodedText(n));
    // otehrwise return the html content
    else
      return n.outerHTML;
    // join them 
  }).join('')
)
2
Community 23 mai 2017 à 10:29

Que diriez-vous:

str='This is a sample url : http://example.com.\nThese are some images:\n<img src="http://example.com/sample1.png" class="sample-image" />\n<img src="http://example.com/sample2.png" class="sample-image" />\nAnother url http://example2.com';

str= str.replace(/[^"](https?:\/\/[^"\s]+)/g, '<a href="$1">$1</a>');
console.log(str);

Sortie:

This is a sample url :<a href="http://example.com.">http://example.com.</a>
These are some images:
<img src="http://example.com/sample1.png" class="sample-image" />
<img src="http://example.com/sample2.png" class="sample-image" />
Another url<a href="http://example2.com">http://example2.com</a>
0
Toto 14 janv. 2017 à 11:51