简体   繁体   English

使用正则表达式替换 Angular 模板中字符串中的字符

[英]Using a regex to replace characters in a string in an Angular template

I know that I can normally use myString.replace(/\*/g, '') to remove * from a string.我知道我通常可以使用myString.replace(/\*/g, '')从字符串中删除* But I cannot seem to make that work in a Angular HTML template.但我似乎无法在 Angular HTML 模板中完成这项工作。 Here is what I doing...这就是我在做什么...

<div class="panel panel--raised">
  <div class="row">
    <div class="form-group col-md-6">
      <div class="form-group__text">
        <input type="text" placeholder="Search... (min of 3 characters)" [(ngModel)]="searchString" minlength="3">
      </div>
    </div>
    <div class="col-md-6">
      <button class="btn btn--success btn--small host-info-button"
              [disabled]="searchString.replace(/\*/g, '').length < 3"
              (click)="getInfo(searchString)">Search</button>
    </div>
  </div>
</div>

Parser Error: Unexpected token /...

What am I doing wrong here?我在这里做错了什么?

Update:更新:

What I am trying to do is make the user enter at least 3 characters that are not wildcard ( * ) characters.我想要做的是让用户输入至少 3 个不是通配符 ( * ) 字符的字符。 So a** would only count as 1 character and *** would count as zero characters, but *xyz* would count as 3 characters.所以a**只会算作 1 个字符, ***会算作 0 个字符,但*xyz*会算作 3 个字符。 I am not sure that Validator.pattern() would be able to accomplish this, but maybe I am just lacking imagination.我不确定Validator.pattern()是否能够做到这一点,但也许我只是缺乏想象力。

Unfortunately, RegExp literal is not supported by the templating language.不幸的是,模板语言不支持 RegExp 文字。 They should be on your component.它们应该在您的组件上。

More info on Angular Github repo issue: https://github.com/angular/angular/issues/21978有关 Angular Github 回购问题的更多信息: https://github.com/angular/angular/issues/21978

For this particular case, you can set up pattern validator and use something like this: Validators.pattern('/\*/g')对于这种特殊情况,您可以设置模式验证器并使用如下内容: Validators.pattern('/\*/g')

in template:在模板中:

[disabled]="isDisabled"

in ts file:在 ts 文件中:

get isDisabled(): boolean {
    return this.searchString.replace(/\*/g, '').length < 3;
}

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

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