JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Vue3解析特殊字符

2024. 03. 21    

Vue3解析特殊字符

Vue3解析日语格式在汉字上添加假名

    body {
      font-size: 16px;
    }
    span {
      word-spacing: -0.3em;
      /* word-spacing: -5px; */
    }
    strong {
      display: inline-block;
      font-weight: normal;
      text-align: center;
      /* font-size: 14px; */
      background-color: bisque;
    }
    em,
    i {
      font-style: normal;
      display: block;
    }
    i {
      font-size: 10px;
      line-height: 1;
    }

  <div id="app">
    <p></p>
    <div v-for="item in arr">
      <span v-html="analysis(item.label)"></span>
      <span></span>
    </div>
  </div>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    const { createApp, ref, computed } = Vue

    createApp({
      setup() {
        const message = ref('Hello vue!')
        let arr = [
          { label: '{嘗}<かつ>て', katakana: 'かつて', translate: '过去' },
          {
            label: '{勉}<べん>{強}<きょう>',
            la: 'べんきょう',
            translate: '学习'
          }
        ]

        const analysis = str => {
          let HTML = ''
          function operationFn(str) {
            if (str.includes('<') || str.includes('{')) {
              // 匹配汉字的前面
              let charFront = splitByFirstRegExpMatch(str, /{/)
              // 匹配汉字的后面
              let charAfter = splitByFirstRegExpMatch(charFront[1], /}/)[0]
              // 匹配假名的前面
              let letter = splitByFirstRegExpMatch(str, /</)[1]
              // 匹配假名的后面
              let letterAfter = splitByFirstRegExpMatch(letter, />/)
              HTML += `
		${charFront[0]}
			<strong>
				<i>${letterAfter[0]}</i>
				<em>${charAfter}</em>
			</strong>
		`
              if (letterAfter[1].includes('<')) {
                str = operationFn(letterAfter[1])
              } else {
                HTML += letterAfter[1]
              }
              console.log(HTML)
              return HTML
            } else {
              return str
            }
          }
          return operationFn(str)
        }
        const splitByFirstRegExpMatch = (string, regexp) => {
          const match = string.match(regexp)
          if (match) {
            const index = match.index + match[0].length
            return [string.slice(0, index - 1), string.slice(index)]
          }
          return [string]
        }

        return {
          analysis,
          message,
          arr
        }
      }
    }).mount('#app')