Home > Enterprise >  Javascript capitalizing string after 2 characters
Javascript capitalizing string after 2 characters

Time:10-29

I have an address that looks like this: 3513 Jones Drive Apt #500a

How do I capitalize any characters that come after Ap to be all caps. Including the a after the apartment number.

3513 Jones Drive APT #500A

I started using indexOf! Any help is appreciated.

NewAddress = toggleCaseText(GetRecordsLF_Address); //3513 Jones Drive Apt #500a
FinalAddress = NewAddress.substring(NewAddress.indexOf('Ap')   1); //needs to be 3513 Jones Drive APT #500A

CodePudding user response:

Use a regular expression replacement with a callback function that converts the match to uppercase.

let NewAddress = '3513 Jones Drive Apt #500a';
let FinalAddress = NewAddress.replace(/Ap.*/, match => match.toUpperCase());
console.log(FinalAddress);

CodePudding user response:

let NewAddress = '3513 Jones Drive Apt #500a';
let FinalAddress = NewAddress.replace(/Ap.*/, match => match.toUpperCase());
console.log(FinalAddress);

CodePudding user response:

You can use a regex replace:

[
  '3513 Jones Drive APT #500A',
  '351 Jones Drive Apt #500a',
  '35 Jones Drive AP #500B',
  '3 Jones Drive Ap #500b',
  '3513 Jones Drive App #500A', // no match
  '43 Apple Blossom Rd.' // no match
].forEach(str => {
  let fixed = str.replace(/\bAPT?\b.*/i, m => m.toUpperCase());
  console.log(str   ' => '   fixed);
});

Output:

3513 Jones Drive APT #500A => 3513 Jones Drive APT #500A
351 Jones Drive Apt #500a => 351 Jones Drive APT #500A
35 Jones Drive AP #500B => 35 Jones Drive AP #500B
3 Jones Drive Ap #500b => 3 Jones Drive AP #500B
3513 Jones Drive App #500A => 3513 Jones Drive App #500A
43 Apple Blossom Rd. => 43 Apple Blossom Rd.

Explanation of regex:

  • \b -- word boundary
  • AP -- expect literal AP
  • T? -- optional T
  • \b -- word boundary
  • .* -- catch everything to end of string
  • /i -- ignore case

You might want to make the regex more strict to avoid false positives, such as /\bAPT?\b #?\w /i

  • Related