【问题标题】:My code should be detecting if a string has currency symbols, but it will not detect £我的代码应该检测一个字符串是否有货币符号,但它不会检测到 £
【发布时间】:2020-07-18 02:22:39
【问题描述】:

我的代码应该检测货币符号,并根据结果执行代码,但代码在任何情况下都不会检测到“£”。以下是相关代码:

let requirements = [ "£", "$" ];
let mcontent = "$£50";
let y = 0;
for (let p = 0; p < requirements.length; ++p) {
    if (mcontent.includes(requirements[p])) {
        ++y;
    }
}
if (y == 1) {
    //this is considered success, only ONE currency symbol was detected. If mcontent = '$50' or '£50', we should be here.
} else {
    //this is considered failure, TWO or ZERO currency symbols were detected. In this scenario, I want the code to fail.
}

我知道这可能不是编写函数以完成我想要完成的任务的最佳方式,因此我愿意为我已有的内容提供更好的想法/修复。

【问题讨论】:

  • 您期待什么?该字符串中有两个货币符号。
  • @hev1 我什至通过重写代码来回答这个问题而没有注意到????
  • @SenseiMunchkin 我无法重现该问题:jsfiddle.net/qkL3zcyp
  • console.log(y) 在你的 if 语句之前,你会看到 2,而不是 1。
  • @SenseiMunchkin 您的问题无法重现(在 nodejs 服务器上打印 2):repl.it/repls/WearableUnderstatedSets#index.js,您缺少详细信息,请尝试创建一个 minimal reproducible example,以便人们可以帮助调试您的代码.您也是说mcontent是用户输入的,请确保您认为是用户输入的£的字符实际上与您的数组中的字符相同。

标签: javascript arrays for-loop if-statement


【解决方案1】:

执行此操作的最简洁方法是使用RegExp 进行检查,如下所示:

if (mcontent.match(/£|\$/g)?.length == 1) { // the question mark is so we don't encounter an error if no matches were found
  // success
} else {
  // failure
}

这是一个活生生的例子:

const mcontent1 = '$£50';
const mcontent2 = '£50';
const mcontent3 = '$50';

const regex = /£|\$/g; // slash to escape $ because it has special meaning in regex

console.log(mcontent1.match(regex).length == 1); // false
console.log(mcontent2.match(regex).length == 1); // true
console.log(mcontent3.match(regex).length == 1); // true

【讨论】:

  • 有没有办法根据需求数组动态改变正则表达式?
  • @LeaftheLegend 提出了与我完全相同的问题。要求写在一个 JSON 文件中,我需要正则表达式来处理我在那里输入的任何内容。
  • 是的。 const regex = new RegExp(requirements.join('|').replace('$', '\\$'), 'g')。由于$RegExp 中具有特殊含义,因此必须用斜线对其进行转义。由于斜线在字符串中具有特殊含义,因此斜线本身必须用斜线进行转义。
  • 您也可以将货币符号放在像new RegExp("[" + ['$','£'].join('') + "]") 这样的字符类中。如果您不限于一组货币符号并希望允许其中任何一个,您可以简单地使用/\p{S}/
  • 但它在行动,只是为了证明我没有撒谎 ;-) regex101.com/r/SSRbg9/1
【解决方案2】:

如果您不想使用正则表达式,只需检查字符串是否包含符号,增加一个计数器,并返回是否正好有 1 个匹配项:

let testA = "$£50",
    testB = "£50",
    testC = "$50";

function checkString(str) {
  const symbols = ["£", "$"];
  let matches = 0;

  for (const symbol of symbols)
    if (str.includes(symbol)) matches++;
      
  return matches == 1;
}

console.log(
  checkString(testA),
  checkString(testB),
  checkString(testC)
);

【讨论】:

  • mcontent变量是用户自己输入的,为了例子我自己放了。这在我的场景中不起作用,我需要 .includes() 函数才能工作。
  • @SenseiMunchkin 嗯?如果它是由用户输入的,那么你可以将它传递给checkString。这就是我在底部使用多个不同输入来调用它的方式。
  • 还有@SenseiMunchkin,这个答案实现了String.includes,所以我也对那个评论感到困惑。
【解决方案3】:

使用 RegExp 它将根据输入的值返回 true 或 flase 这个例子会让你知道如何使用它

const elementTwo = document.getElementById('elementTwo');
elementTwo.addEventListener("input", function(event) {
  pattern = /^[£|$]{1}(\d+)/
  if (pattern.test(this.value)) {
    console.log("found")
  } else console.log("not found")

});
<p>Enter value</p>
<input id="elementTwo" type="text" />

【讨论】:

  • 关键是他们希望它仅在存在恰好一个货币符号时返回false
  • @LeaftheLegend 谢谢你的澄清,我可能误解了
猜你喜欢
  • 1970-01-01
  • 2021-07-05
  • 2010-10-17
  • 2012-09-04
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 2014-12-07
相关资源
最近更新 更多