I'm wanting to check if there are any numbers in the address string but only before 'WA' and then set the cleanAddress var based on the result.
How can I get it to only check before 'WA' so the 6000 doesn't cause it to return TRUE.
And potentially different states so check for "WA" or "NSW" or "VIC" etc...
const address = "123 Smith, Suburb, WA 6000"
var cleanAddress = ""
if(address.match(/^\d $/)) {
cleanAddress = ""
}
else {
cleanAddress = ","
}
Expecting
"123 Smith, Suburb, WA 6000" \\result cleanAddress = ""
"Suburb, WA 6000" \\result cleanAddress = ","
CodePudding user response:
What I would highly recommend in this solution is firstly to see what is the pattern to find the section I would like to check. So in your case I see that there are two(2) commas before the 'WA', or if the case is that it would always be WA I would just split it by 'WA', then take the first split element and check if it contains numbers with the regex. Other way around is firstly to find the commas in the regex, then to get through lastindexof function (
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)
CodePudding user response:
You can test
for the following pattern:
(\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
CodePudding user response:
If you only want to test for the occurrence, you can use .test()
and a match without any lookarounds:
\d.*?\b(?:WA|NSW|VIC)\b
Explanation
\d
Match a digit.*?
Match any character without a newline, as few as possible\b(?:WA|NSW|VIC)\b
Match any of the alternatives between word boundaries
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}'`);
})