【问题标题】:Get first specific special character that occurs in a string获取字符串中出现的第一个特定特殊字符
【发布时间】:2018-05-19 18:40:10
【问题描述】:

如何从字符串中提取第一个特殊字符(仅允许 #.)?

例如:

svg#hello 将返回 #

-hello-world#testing 将返回 #

-hello-world.testing 将返回 .

.test 将返回 .

等等?

【问题讨论】:

标签: javascript


【解决方案1】:

您可以在字符串上使用.match(/[#.]/) 来匹配您想要的字符:

var texts = ['svg#hello', '-hello-world#testing', '-hello-world.testing', '.test'];
var regex = '[#.]';

// You need to add the [0] to get the element of the array returned by the function
console.log(
  texts[0].match(regex)[0],
  texts[1].match(regex)[0],
  texts[2].match(regex)[0],
  texts[3].match(regex)[0]
);

如果您想将其扩展到其他特殊字符,您可能需要在字符串上使用像 .match(/[^a-zA-Z0-9-]/) 这样的反向正则表达式来匹配非字母、非数字而不是 - 字符:

var texts = ['svg#hello', '-hello-world#testing', '-hello-world.testing', '.test', '_new-test'];
var regex = '[^a-zA-Z0-9-]';

// You need to add the [0] to get the element of the array returned by the function
console.log(
  texts[0].match(regex)[0],
  texts[1].match(regex)[0],
  texts[2].match(regex)[0],
  texts[3].match(regex)[0],
  texts[4].match(regex)[0]
);

希望对你有帮助。

【讨论】:

  • 你为什么不在 adeneo 的评论中使用正则表达式?该问题明确表示“只允许#.”。
  • 我承认我在阅读问题时一定错过了它。我已经编辑了,谢谢@DavidKnipe
猜你喜欢
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 2013-03-16
  • 2015-10-28
  • 2011-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多