Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

javascript - Correct way of handling multiple housenumber options possible regex

I'm looking for help refactoring this messy code part. It should handle the following house number formats

  • 54 6 K 1 -> 546 K 1
  • 54 6k 1 -> 546 K 1
  • 20 H L -> 20 H L
  • 1 10 -> 1 10
  • 546 k1 -> 546 K 1
  • 1K -> 1 K
    ?.toUpperCase()
    ?.match(/[^a-z]+|[a-z]|[a-z]/gi)
    ?.map((part) => `${part.trim()} `) // Split each part with a space
    .toString() // Revert to one string
    .replace(/,/g, "") // Remove all commas
    .replace(/s+/g, " ") // Remove duplicate spaces
    .trim(); // Remove and spaces

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use

function foo(input) {
  return !/[a-z]/i.test(input) ? input : input
    ?.toUpperCase()
    ?.match(/[^a-zs]+|[a-z]/gi)
    .join("") // Revert to one string
    .replace(/(?<=D)|(?=D)/g, ' '); // Add spaces before/after a non-digit
}

console.log(foo("54 6 K 1"));
console.log(foo("54 6k 1"));
console.log(foo("20 H L"));
console.log(foo("1 10"));
console.log(foo("546 k1"));
console.log(foo("1K"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...