简体   繁体   English

AngularJS 过滤器去除某个正则表达式

[英]AngularJS filter to remove a certain regular expression

I am attempting to make an angularJS filter which will remove timestamps that look like this: (##:##:##) or ##:##:##.我正在尝试制作一个 angularJS 过滤器,它将删除看起来像这样的时间戳:(##:##:##) 或 ##:##:##。

This is a filter to remove all letters:这是一个删除所有字母的过滤器:

.filter('noLetter', function()  {
//this filter removes all letters
        return function removeLetters(string){
        return string.replace(/[^0-9]+/g, " ");
        }
        })

This is my attempt to make a filter that removes the time stamps, however it is not working, help is much appreciated.这是我尝试制作一个删除时间戳的过滤器,但是它不起作用,非常感谢帮助。

.filter('noStamps', function () {
  return function removeStamps(item) {
  return item.replace(/^\([0-9][0-9]:[0-9][0-9]:[0-9][0-9]\)$/i, "");
 }
})

My goal is for it to delete the timestamps it finds and leave nothing in their place.我的目标是删除它找到的时间戳,不留任何东西。

edit based on question in comments: The time stamps are in the text so it would say "this is an example 21:20:19 of what I am 21:20:20 trying to do 21:20:22"根据评论中的问题进行编辑:时间戳在文本中,因此它会说“这是我在 21:20:20 尝试做的 21:20:22 的示例 21:20:22”

I would want this to be converted into "this is an example of what I am trying to do" by the filter.我希望通过过滤器将其转换为“这是我正在尝试做的事情的一个示例”。

You may use您可以使用

/\s*\(?\b\d{2}:\d{2}:\d{2}\b\)?/g

See regex demo正则表达式演示

Thre main points:三个要点:

  • The ^ (start of string) and $ (end of string) anchors should be removed so that the expression becomes unanchored, and can match input text partially.应该删除^ (字符串开头)和$ (字符串结尾)锚点,以便表达式变得非锚定,并且可以部分匹配输入文本。
  • Global flag to match all occurrences匹配所有出现的全局标志
  • Limiting quantifier {2} to shorten the regex (and the use of a shorthand class \\d helps shorten it, too)限制量词{2}以缩短正则表达式(并且使用速记类\\d有助于缩短它)
  • \\)? and \\(? are used with ? quantifier to match 1 or 0 occurrences of the round brackets.\\(??量词一起使用以匹配 1 或 0 次出现的圆括号。
  • \\s* in the beginning "trims" the result (as the leading whitespace is matched). \\s*在开头“修剪”结果(因为匹配前导空格)。

JS snippet: JS片段:

 var str = 'this is an example (21:20:19) of what I am 21:20:20 trying to do 21:20:22'; var result = str.replace(/\\s*\\(?\\b\\d{2}:\\d{2}:\\d{2}\\b\\)?/g, ''); document.getElementById("r").innerHTML = result;
 <div id="r"/>

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

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