代码之家  ›  专栏  ›  技术社区  ›  Glory Raj

搜索字符串中包含多个角4字符的字符

  •  0
  • Glory Raj  · 技术社区  · 7 年前

    我有两个字符串,如“l7-lo”和“l7-lo”。

    如果字符串只包含“-”我需要在此基础上进行一些处理,如果字符串包含这两个字符“-”,“%”我只需要考虑%和忽略“-”字符。

    为了这个目的,我在下面这样做了

       if (this.selectedSources[formula].Value.indexOf('%') == -1) {
        this.formulaType = "percent"
      }
      else if (this.selectedSources[formula].Value.indexOf('-') == -1) {
        this.formulaType = "diff";
      }
    

    但是上面的代码有些不起作用。

    如果角上有两个字符,你能告诉我如何只区分一个字符吗

    2 回复  |  直到 7 年前
        1
  •  1
  •   Sunil Singh    7 年前

    是否应更改条件。休息很好-

    if (this.selectedSources[formula].Value.indexOf('%') !== -1) {
        this.formulaType = "percent"
     }
      else if (this.selectedSources[formula].Value.indexOf('-') !== -1) {
        this.formulaType = "diff";
     }
    
        2
  •  1
  •   Brandon Taylor    7 年前

    如果你需要测试两者 % - 在字符串中,我将使用regex:

    const regex = new RegEx(/.*[%]{1}.*[-]{1}/);
    this.formulaType = regex.test(this.selectedSources[formula].Value) ? 'percent' : 'diff';
    

    否则,您只能使用 .indexOf('%') :

    this.formulaType = this.selectedSources[formula].Value.indexOf('%') !== -1
      ? 'percent'
      : 'diff';
    
    推荐文章