I'm trying to work out in javascript / jquery how to capitalise the first 3 characters of a string, if that string starts with one of several matches.
In php I can do:
$loc = (preg_match("/^(nww|nsw|esw|sew|wes)/i", $loc)) ? strtoupper( substr( $loc, 0, 3 ) ).substr( $loc, 3 ) : ucfirst($loc);
Which would change nsw48751
to NSW48751
, but change newlease to Newlease.
How can I do this in javascript or jquery ?
Thanks
One option is to alternate between matching any of those 3 letters, and if none of those are found, match the first letter in the string. Then, use a replacer function to capitalize the match:
const change = str => str.replace(/^(?:nww|nsw|esw|sew|wes|[a-z])/i, match => match.toUpperCase());
console.log(change('nsw48751'));
console.log(change('newlease'));