简体   繁体   English

如何从文本中删除字符串

[英]How to remove string from text

I have a string that contain numbers separated by the dots eg: "2.3.19" or "56.3.10", etc我有一个包含由点分隔的数字的字符串,例如:“2.3.19”或“56.3.10”等

Sometime string might contain text say "33.4.5.6-any-text-here".有时字符串可能包含文本“33.4.5.6-any-text-here”。

How would you strip the non-numeric text from the string leaving just numbers separated by the dots?您将如何从字符串中去除非数字文本,只留下由点分隔的数字?

I've tried this solution: Number(("33.4.5.6any-text-here").match(/\d+$/));我试过这个解决方案: Number(("33.4.5.6any-text-here").match(/\d+$/)); but that returns 0但返回0

This should work:这应该有效:

"33.4.5.6-any-text-here".match(/[0-9.]*/)[0]
  • [0-9.] matches any number 0-9, and the dot (.). [0-9.]匹配任何数字 0-9 和点 (.)。
  • * matches 0 or more of the previous pattern (digit or dot). *匹配 0 个或多个先前的模式(数字或点)。
  • Since match always returns an array in this case (when the 'g' flag is not used in the regex) we can safely return the first item of the array ( [0] ).由于match在这种情况下总是返回一个数组(当 'g' 标志未在正则表达式中使用时),我们可以安全地返回数组的第一项( [0] )。 It always returns an array in this case because we said "zero or more".在这种情况下,它总是返回一个数组,因为我们说“零个或多个”。 Thus, if zero, it matches nothing and returns an empty string if nothing is found.因此,如果为零,则不匹配任何内容,如果未找到任何内容,则返回空字符串。

 let str = "33.4.5.6-any-text-here" let finStr = str.replace(/[^\d.]/g, ''); //.replace(/[^\d|^\.]/g, '') console.log(finStr); // 33.4.5.6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM