今天很开心, 写了一个 解析html 富文本的方法, 就是将html格式的富文本解析成cocos 的富文本格式

//解析html 富文本 为 cocos 的富文本
parsingHTMLRichText(htmlRichText,bgColor) {
if(htmlRichText.length <= 0 || typeof(htmlRichText) != ‘string’) return
//解析出来的文本
let myRichText = ‘’
//背景底色
//背景底色
var bgColor = bgColor == null || bgColor == ‘’ ?
‘<color=#FFFFFF>’
: ‘<color=’ + bgColor + ‘>’
//是否开始找颜色参数 记录颜色的文本
var isFindColor = false
var colorStr = ‘’
//开始找 <> 开头和结尾括号 的位置
var isFindFormat = false
var startIndex = 0
var endIndex = 0
var formatString = ‘’

myRichText += bgColor
for(var i = 0 ; i < htmlRichText.length; i ++){

//找特殊标签 开始的标签
if(htmlRichText[i] == '<'){
  isFindFormat = true
  startIndex = i
}

//是否开始找颜色
if(isFindFormat == true && htmlRichText[i] == '#'){
  isFindColor = true
 
}

//如果开始找颜色了
if( isFindColor == true){
  colorStr += htmlRichText[i]
  //结束找颜色
  if(colorStr.length == 7){
    isFindColor = false
  }
  continue
}

//找到特殊标签 结束的标签  
if(htmlRichText[i] == '>'){
  isFindFormat = false
  endIndex = i
  //截取这段特殊格式的字符串
  formatString = htmlRichText.slice(startIndex,endIndex)
  //如果是这个字符就添加背景色
  if(formatString == '</span'){  
    myRichText +=  bgColor
  }else{
    //否则添加 找到的特殊颜色
    if(isFindColor == false){
      myRichText +=  '</c><color=' +  colorStr + '>'
      colorStr = ''
    }
  }
  continue
}

if(isFindFormat == false &&  isFindColor == false ){
  myRichText += htmlRichText[i]
}

}

myRichText += '</c>'
return myRichText

},

2赞

欢迎指教更好的代码

1赞

可以哦 chris