Transitioning from application development to web development here so I am still trying to figure everything out.
How do you change only the color of Chinese characters in the page title and menu from WordPress? It should be done in the css, but I wasn’t sure how to detect Chinese characters that way. Any insight would be greatly appreciated!
CSS is not a programming language and therefore does not have the ability to detect Chinese characterâthis has to be done by using regex to filter individual characters on your page by their Unicode character range, and pick out those that fall within the CJKUI block. This range is very well discussed in another SO question here. To summarise the range:
u4E00
tou9FFF
u3400
tou4DFF
u20000
tou2A6DF
uF900
touFAFF
u2F800
tou2FA1F
The first range would usually suffice, but if you are working with Chinese texts containing rare, dated characters then expanding your selection to include the full CJKUI range is favourable.
However, by using regex on a large amount of text you are performing an expensive matching operationâstill feasible for small snippets for texts where you know for sure Chinese characters will turn up. The trick is to detect the Unicode range (it is asked in the Python tag but also works for JS) of each character iteratively, and wrap it within a
<span lang="zh">
element (using thelang
attribute is semantically valid and recommended) with a specific class so that you can style it anyway you desire using CSS.For the regex pattern, the trick is to use the character range selector:
[...-...]
(read more here). For the most reduced CJKUI set, you can use[u4E00-u9FFF]
. However, as mentioned before if you want to really match to all possible Chinese unicode characters, you will have to use the full set:[u4E00-u9FFFu3400-u4DFFu20000-u2A6DFuF900-uFAFFu2F800-u2FA1F]
The best solution though, is to pre-process your HTML/user input with regex once, which will do the same as above, so that runtime regex wrapping of Chinese character can be avoided.