【问题标题】:How to replace dashes with spaces, and double dashes with dashes?如何用空格替换破折号,用破折号替换双破折号?
【发布时间】:2015-04-20 15:58:22
【问题描述】:

我在 Meteor 中写了一个人的 CRUD,我想要漂亮的 URL,比如

www.mysite.com/John-Doe。

(实际上,我真正的偏好是 www.mysite.com/JohnDoe,但实现起来可能有点困难。)

为了做到这一点,我需要能够将“John-Doe”翻译成“John Doe”以及“John-Doe--Smith”John Doe-Smith”。

我当然可以将“--”初步替换为一些临时字符,但要寻找更优雅的解决方案。

(编辑:写完这篇文章后,我才意识到我可以清理名称以首先将多个空格和破折号折叠成一个;但我现在对更通用的答案感到好奇)。

【问题讨论】:

  • 或者有没有更漂亮的名字编码方式?
  • 试过"a--b".replace(/-(?!-)/g, ' '),但它返回"a- b"。什么是替换所有 single 破折号的正则表达式,同时保留多个破折号?
  • 我最终用下划线代替了空格,而不是破折号:“John_Doe-Smith”。不过,我的问题仍然存在。

标签: regex meteor


【解决方案1】:

您可能想查看underscore.string 库,Meteor 可以使用meteor add underscorestring:underscore.string

// Replace dashes with spaces:
s.humanize("no-dash");
// => "no dash"

// Dashes to camel case:
s.camelize("John-Doe");
// => "JohnDoe"

// Double dashes to single dashes:
s.replaceAll("John-Doe--Smith", "--", "-");
// => "John-Doe-Smith"

// Join two names with dashes:
s.join("-", "John", "Doe");
// => "John-Doe"

在许多情况下,有多种方法可以达到相同的结果,包括比上述方法更优雅或更量身定制的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2013-10-09
    • 2013-01-14
    • 1970-01-01
    相关资源
    最近更新 更多