【问题标题】:Highlight symbols and numbers with Highlight.js使用 Highlight.js 突出显示符号和数字
【发布时间】:2020-12-14 14:01:48
【问题描述】:

我想使用highlight.js 库,‏ 而且我无法突出显示+ 符号和数字(例如1000)。 有没有办法做到这一点?‏

import React, { Component } from 'react'
import hljs from 'highlight.js'

export default class App extends Component {
  constructor(){
    super();
    this.state = {
    }
  }

  componentDidMount(){
    hljs.registerLanguage("pl", function(hljs) {
      return {
        case_insensitive: false,
        keywords: {
        literal: '--',
        symbols: '+',
        keyword0: ' minus # plus   ++ $_  ',
       operator:' 1 2 3 4 /+ ',
       numbers: '/[0-9]+?/',
        keyword1: ' THEMENBEREICH ZEIT AUS BIS GIB HAT IST MAX MIN MIT TYP VAR VON'
        
        },
      contains: [
          {
            className: 'string',
            begin: "'",
          end: "'",
         // contains: [hljs.BACKSLASH_ESCAPE]
          },
          
      hljs.COMMENT(
            '"', // begin
            '"'  // end
      )
        ]
    };
    })

  }

  updateCodeSyntaxHighlighting = () => {
    document.querySelectorAll("pre code").forEach(block => {
      hljs.highlightBlock(block);
    });
  };
  
handle(event){
    this.setState({
        data:event.target.value
  })
}

  render() {
    let eingabe = this.state.data
     return (
      <div>
        <textarea cols="30" rows="5" type="text"  onChange={this.handle.bind(this)}/>
        <br/>
        <button   onClick={this.updateCodeSyntaxHighlighting.bind(this)}>   clik   </button>
        <pre><code class="pl"> 
       
        {this.state.data} 
        </code></pre>
          
      </div>
    )
  }
}

【问题讨论】:

  • 查找keywords.$pattern的文档...如果您使用各种奇怪的字符,您必须设置一个正则表达式来匹配关键字...默认为\w+,这将仅匹配a-z_- 等...并且您不能在关键字中使用正则表达式,只能使用字符串。 + 不包含在 \w 中,因此它永远不会匹配为关键字。您可能只想考虑多种模式,而不是尝试使用关键字做所有事情。
  • beginKeywords 也可能对您有很大帮助(在模式内)。

标签: javascript highlight.js


【解决方案1】:

制定单独的规则,而不是使用keywords

contains: 
[
  { 
    className: "number",
    begin: /\d+/
  },
  {
    className: "symbol",
    begin: /+/
  }
]

等等

或者您可以尝试keywords.$pattern = /\S+/,即关键字是任何不包含空格的连续字符列表...

https://highlightjs.readthedocs.io/en/latest/language-guide.html#keywords

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多