【发布时间】:2022-01-05 15:09:35
【问题描述】:
我已经阅读了great article 如何在 SVG-Circles 中定位和缩放文本。那里显示的文本换行算法使用以下代码行:
const words = text.split(/\s+/g); // To hyphenate: /\s+|(?<=-)/
这个sn-p的想法是用“Self-Sizing Text in a Circle”这个词创建一个列表 -> [“Self-Sizing”, “Text”, “in”, “a”, “圆”]。
^^该算法的工作原理就像一个魅力,但连字符版本在 Safari 中不起作用:
const words = text.split(/\s+|(?<=-)/g); // Not working in Safari
无效的正则表达式:无效的组说明符名称
结果应该是 ["Self-", "Sizing", "Text", "in", "a", "Circle"]。请注意“Self-Sizing”的拆分,将连字符保留为第一个单词的一部分。
为了让示例在所有浏览器中运行,我提出了这个解决方案:
text = text.replace(/-/g, "- "); // add a space next to the hyphen
const words = text.split(/\s+/g); // split using spaces
然而,以正则表达式独有的方式解决这个问题似乎是最优雅的,尤其是在扩大用于换行的字符范围时。
因此,作为一个社区,我想问问你们是否有更好的想法。
可以在 here(helpers.js -> 第 7 行)找到完整的 Playground,或者您可以查看下面的 Stack Snipped:
const text = "Self-Sizing Text in a Circle";
const words = text.split(/\s+|(?<=-)/g);
console.log(words);
【问题讨论】:
-
我认为您应该为您的问题添加更多背景知识。
-
const words = text.match(/[^\s-]+-*/g)可能就是您所需要的,如果您只想提取内部没有-但末尾可以有-的非空白块。 -
@WiktorStribiżew - 哦,那真是太酷了。
-
在这种情况下,
const words = text.match(/[^\s-]+-?|-/g)可能更精确。它将匹配除空格和-之外的任何一个或多个字符,然后匹配一个可选的-或-字符。 -
Leon,请说明你想用
-A--B--这样的刺痛做什么?
标签: javascript regex safari regex-lookarounds