javascript 检查部分字符串是否包含任何数字

h5qlskok  于 2022-12-10  发布在  Java
关注(0)|答案(5)|浏览(156)

我想检查地址字符串中是否有任何数字,但只在'WA'之前,然后根据结果设置cleanAddress变量。
我怎样才能让它只在'WA'之前检查,这样6000就不会导致它返回TRUE。
以及可能不同的州,因此请检查“WA”或“NSW”或“维克”等...

const address = "123 Smith, Suburb, WA 6000"
        var cleanAddress = ""

        if(address.match(/^\d+$/)) {
          cleanAddress = ""
         }
         else {
          cleanAddress = ","
         }

预期

"123 Smith, Suburb, WA 6000"    \\result cleanAddress = ""

"Suburb, WA 6000" \\result cleanAddress = ","
piwo6bdm

piwo6bdm1#

在此解决方案中,我强烈建议首先查看要查找的部分的模式。(2)逗号在“WA”之前,或者如果情况是它将始终是WA,我将用“WA”将其分开,然后使用正则表达式检查第一个拆分元素是否包含数字。另一种方法是首先找到正则表达式中的逗号,然后通过lastindexof函数(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex),然后从lastindexof(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)的第一个字符到数字进行切片,然后使用正则表达式来表示数字。

33qvvth1

33qvvth12#

可以使用下面的正则表达式获取任何检查文本之前的数字。
\b\d+\b(?=.*\bWA)

const address = "200 Smith, Suburb, WA 6000"
var cleanAddress = ""

function checkNumberBefore(text, checkText){
  return address.match("\\b\\d+\\b(?=.*\\b" + checkText + ")");
}

var result = checkNumberBefore(address, 'WA');

console.log(result)
fkaflof6

fkaflof63#

您可以test为以下模式:

(\d+.+) // One or more digits followed by one or more other characters
(?=(?:WA|NSW|VIC)) // Lookahead to find a (non-capturing group) of possible states
const re = /(\d+.+)(?=(?:WA|NSW|VIC))/;

function tester(address, re) {
  return re.test(address) ? '' : '.';
}

console.log(tester('123 Smith, Suburb, WA 6000', re)); // true
console.log(tester('Suburb, VIC 6000', re)); // false
console.log(tester('8 Somewhere Lane, LA 90210', re)); // true
console.log(tester('800 Bob Street, NSW 1000', re)); // false
gev0vcfq

gev0vcfq4#

如果您只想测试出现的次数,可以使用.test()和match,而不需要任何lookarounds:

\d.*?\b(?:WA|NSW|VIC)\b

说明

  • \d匹配数字
  • .*?匹配不带换行符的任何字符,尽可能少
  • \b(?:WA|NSW|VIC)\b匹配单词边界之间的任何替代项
const regex = /\d.*?\b(?:WA|NSW|VIC)\b/;
strings = [
  "123 Smith, Suburb, WA 6000",
  "Suburb, WA 6000"
].forEach(address => {
  let cleanAddress = regex.test(address) ? "" : ","
  console.log(`cleanAddress:'${cleanAddress}'`);
})
egdjgwm8

egdjgwm85#

const address = "123 Smith, Suburb, WA 6000";
var cleanAddress = "";

// Find the position of 'WA' in the string
var index = address.indexOf("WA");

// Get the part of the string that comes before 'WA'
var substring = address.substring(0, index);

// Use a regular expression to check if the substring contains any numbers
var regex = /\d/;
var containsNumbers = regex.test(substring);

if (containsNumbers) {
  // If the substring contains numbers, set cleanAddress to an empty string
  cleanAddress = "";
} else {
  // If the substring does not contain numbers, set cleanAddress to a comma
  cleanAddress = ",";
}

console.log(cleanAddress);

此代码首先使用indexOf()和substring()方法获取字符串中位于'WA'之前的部分。然后使用正则表达式检查子字符串是否包含任何数字。如果子字符串不包含数字,则代码将cleanAddress设置为逗号(,),否则将cleanAddress设置为空字符串。

相关问题