[英]JS Split String By Multiple Paired Delimiters
I have this string that I split whenever it finds two colons.我有这个字符串,只要它找到两个冒号,我就会将其拆分。
"for exam:ple thi:s string turns into" ["for exam","pls thi", "s string turns into"] "for example:ple thi:s 字符串变成" ["for exam","pls thi", "s 字符串变成"]
I do this with:我这样做:
text.split(/(:.*?:)/g)
Afterward I interpret a string as "inside" the delimiter if it contains the characters I expect and none of those I don't.之后,如果一个字符串包含我期望的字符并且没有我不期望的字符,我将其解释为分隔符“内部”。
How do I make it also extract another delimiter like $$...$$ as well as the original:...: but also include the delimiter somewhere so I can use different logic for it?我如何让它也提取另一个分隔符,如 $$...$$ 以及原始的:...:但也在某处包含分隔符,以便我可以使用不同的逻辑?
For context I'm parsing text into different react components.:...: includes addresses to embed a certain component, while $$...$$ includes MathJax.对于上下文,我将文本解析为不同的反应组件。:...: 包括嵌入特定组件的地址,而 $$...$$ 包括 MathJax。
UPDATED更新
You can try this regex with particular checks for :...:
and $$...$$
patterns您可以尝试使用此正则表达式对
:...:
和$$...$$
模式进行特定检查
const text = "for exam:ple thi:s string $$turns$$ into" const partialStrings = text.split(/(:.*?:|\$\$.*?\$\$)/g) for (const partialString of partialStrings) { if (partialString.startsWith(":")) { //TODO: Do your logic with `:...:` pattern console.log(partialString + " contains ':...:'") continue } if (partialString.startsWith("$$")) { //TODO: Do your logic with `$$...$$` pattern console.log(partialString + " contains '$$...$$'") continue } //no patterns console.log(partialString + " has no patterns") }
OLD ANSWER旧答案
You can simply split your string with :
您可以简单地将字符串拆分为
:
const data = "for exam:ple thi:s string turns into" console.log(data.split(":"))
If you want to have similar behavior for $$
and a reusable function, you can declare a function called splitBy
如果你想对
$$
和可重复使用的 function 有类似的行为,你可以声明一个名为 splitBy 的splitBy
const splitBy = (data, delimiter) => { return data.split(delimiter) } const data = "for exam$$ple thi$$s string turns into" console.log(splitBy(data, "$$"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.