Asins Blog

简单其实不简单

This project is maintained by asins

var scripttext = `
    <script type="text/javascript">
        alert('1');
    </script>

    <div>Test</div>

    <script type="text/javascript">
        alert('2');
    </script>
`

function getContentStr(tagName, content) {
  const startTag = '<' + tagName
  const startTagLen = startTag.length
  let startIndex = content.indexOf(startTag) + startTagLen;
  let tagContent = ''

  if (startIndex >= startTagLen && content.length > startTagLen) {
    while (content[startIndex++] !== '>') { }
    const endIndex = content.lastIndexOf(`</${tagName}>`)
    if(endIndex > -1) {
      tagContent = content.slice(startIndex, endIndex);
    }
  }
  return tagContent
}

console.time('正则')
re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts  = re.exec(scripttext);
console.log('正则结果:', scripts[1]);
console.timeEnd('正则');

// script
console.time('字符');
var jsContent = getContentStr('script', scripttext)
console.log('字符结果:', jsContent);
console.timeEnd('字符')

image-20180717183146826

性能差距还是很大的,