React 使用子脚本和超级脚本将字符串转换为元素
React convert a string into element with sub and super scripts
我正在尝试制作一个功能组件,基本上将字符串中的 ^ 和 _ 字符转换为子脚本和超级脚本。这里有一些例子。
'example_3' -> <h1>example<sub>3<sub/><h1/>
标签应以“_”或“^”开头,并在下一个非数字字符处结束标签。
'another_1234Example' -> <h1>another<sub>1234<sub/>Example<h1/>
也应该能够处理任意数量的数字
'something^2else_34' -> <h1>something<sup>2<sub/>else<sub>34<sub/> <h1/>
方案一(过于复杂):
const string = "another_1234Example_348jiwf_342";
console.log(
(string.trim() + " ")
.split("_")
.join("<sub>")
.split(/(?<=<sub>\d+)(?!\d)/g)
.join("</sub>")
);
拆分_
这将return一个数组,之后加入一个<sub>
。比使用正则表达式检查它是否与开头的数字匹配 <sub>
.
Link 到正则表达式:https://regex101.com/r/RFkEQa/1
方案二(推荐):
这种东西最好用replace。参考这个post:
const string = "another_1234Example_348jiwf_342";
console.log(string.replace(/(_\d+)/g, "<sub>$&</sub>").replace(/_/g, ""));
我正在尝试制作一个功能组件,基本上将字符串中的 ^ 和 _ 字符转换为子脚本和超级脚本。这里有一些例子。
'example_3' -> <h1>example<sub>3<sub/><h1/>
标签应以“_”或“^”开头,并在下一个非数字字符处结束标签。
'another_1234Example' -> <h1>another<sub>1234<sub/>Example<h1/>
也应该能够处理任意数量的数字
'something^2else_34' -> <h1>something<sup>2<sub/>else<sub>34<sub/> <h1/>
方案一(过于复杂):
const string = "another_1234Example_348jiwf_342";
console.log(
(string.trim() + " ")
.split("_")
.join("<sub>")
.split(/(?<=<sub>\d+)(?!\d)/g)
.join("</sub>")
);
拆分_
这将return一个数组,之后加入一个<sub>
。比使用正则表达式检查它是否与开头的数字匹配 <sub>
.
Link 到正则表达式:https://regex101.com/r/RFkEQa/1
方案二(推荐):
这种东西最好用replace。参考这个post:
const string = "another_1234Example_348jiwf_342";
console.log(string.replace(/(_\d+)/g, "<sub>$&</sub>").replace(/_/g, ""));