Home > Mobile >  Handle slicing and formatting strings with regex and Vue
Handle slicing and formatting strings with regex and Vue

Time:12-08

I have an issue when code vue, with string:

しらべよう、まとめよう ≪A≫[B]きものの ≪C≫[D]≪E≫[F]

I need processing to be able to render something like this:

the text above will be the text inside []. then the bottom will start with the letter inside ≪≫, and finally the remaining letter.

...(if have)
 <ruby>B
   <rt>A</rt>
 </ruby>
... (if have)
<ruby>D
 <rt>C</rt>
</ruby>
... (if have)

https://codepen.io/AkiraGosho/pen/NWaNNrZ?editors=1111

This is my demo, but I only got 1 letter, so I don't know how to satisfy the problem

Thank you very much.

CodePudding user response:

You can do this using .replace, here is an example:

const input = 'しらべよう、まとめよう ≪A≫[B]きものの ≪C≫[D]≪E≫[F]'
const output = input.replace(/([^≪]*)≪(.)≫[^\[]*\[(.)\]/g, '$1\n<ruby>$3\n\t<rt>$2</rt>\n</ruby>\n');
console.log(output);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

What this does, is to use a regex that splits the input into groups, the first group ([^≪]*) selects any character that is not a fallowed by , then, the second group (.) selects a character preceded by and fallowed by . The third group uses the same logic but instead of using and , it uses [ and ].

  • Related