RegEx pattern to always uppercase "CA" and "USA" in address string - javascript

end_address = 'joe place, 555 test street, sacramento, ca, usa 95814';
end_address = end_address.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
The final result of this is:
Joe Place, 555 Test Street, Sacramento, Ca, Usa 95814
but my desired output is:
Joe Place, 555 Test Street, Sacramento, CA, USA 95814
How can I match a string so that "CA" and "USA" are always uppercase like the desired output?

This will work:
end_address = 'jOe place, 555 test street, sacramento, ca, usa 95814'.toLowerCase();
end_address = end_address.replace(/\b(usa\b|ca\b|\w)/g, function(txt) { return txt.toUpperCase(); });
alert(end_address);
First, I lowercase it all, then apply the capitalization regex, /\b(usa\b|ca\b|\w)/g, which looks for the start of a word. It will match, then capitalize "usa", "ca" or the first character of the word.

Assuming the pattern will always be the same, you need to do a second pass at the string.
var result = end_address
.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}).replace(/(\w{2}), (\w+) (\d{5}(-\d{4})?)$/, function(match, state, country, zip) {
return state.toUpperCase() + ", " + country.toUpperCase() + ", " + zip;
});

What I'd do is something like this:
address = address.replace(
/([a-z]{2}),\s*([a-z]{3})\s*(\d{5})$/i,
function(match, state, country, zip) {
return state.toUpperCase() + ", " + country.toUpperCase() + " " + zip;
})
It'll do the replacement in one pass, and will only touch the state/country (assuming those are at the end of the string).
See the regex work on Regex101

Related

How to use Regex to capitalize a street address?

In my application, you can submit a street address, and in the front end I convert it all to lowercase to be stored in the database. Now when I fetch the data I get an address that looks like:
"1 pleasant valley drive"
Can I make a regex to capitalize the first letter of each word in the string?
End goal:
"1 Pleasant Valley Dr"
I'm currently using:
let addrFormat =
address?.split(" ")[0] +" " +
address?.split(" ")[1].charAt(0).toUpperCase() +
address?.split(" ")[1].substring(1) +
" " + address?.split(" ")[2].charAt(0).toUpperCase() +
address?.split(" ")[2].substring(1);
but I need it to scale. lets say the street address is:
1234 Rocky Mountain Road
Then I have a problem with my code because it wont capitalize the last word.
You can simply uppercase the letters that aren't proceeded by a word character.
This can be checked with a word-boundary \b
let address = "1 pleasant valley drive";
address = address.replace(/\b(\w)/g, (m,g) => g.toUpperCase())
console.log(address);

How to remove all the white spaces between two words?

I have an input field on which the user types the city name, but what if the user types the city like this:
"New York "
" New York "
I used the trim function but that did not work, any suggestion?
const city = "New York ";
console.log(city.trim());
How can I remove all the white spaces so I can save the city in the state as "New York"?
You can also use replace to replace all consecutive space characters with one space:
const str = "New York "
" New York "
const res = str.replace(/\s+/gm, " ").trim()
console.log(res)
Alternatively, you can split the string by a space, filter out the empty items, then join back by a space:
const str = "New York "
" New York "
const res = str.split(" ").filter(e=>e).join(" ")
console.log(res)
Combine the string.replace() method and the RegEx and replace it with a single string. Notice the starting and ending spaces will be kept and stripped down to a single space. Trim any surrounding spaces from the string using JavaScript’s string.trim() method
const city = " New York ";
console.log(city.replace(/\s+/g, ' ').trim());

Handle exceptions in a function that converts a camelCase string to a Formated String in Javascript

So, I've made a function that converts a camelCasedString to a Properly Formatted String using some answer here on Stack Overflow.
This is the function:
function camelCaseToString(str){
var a = str.replace( /([A-Z])/g, " $1" );
var b = a.charAt(0).toUpperCase() + a.slice(1);
return b;
}
problem is some outputs are not as I expect them to be, for example, these are wright:
camelCaseToString('exampleText'); // Example Text
camelCaseToString('ExampleText'); // Example Text
camelCaseToString('string(parenthesis)'); //String (parenthesis)
but I expect these:
camelCaseToString('string (Parenthesis)'); //gives String ( Parenthesis)
camelCaseToString('exampleWithRomanNumbersIII'); //gives Example With Roman Numbers I I I
to be String (Parenthesis) and Example With Roman Numbers III respectively.
Is there a way to to this with Regex? For the parenthesis case, I can simply use replace('( ', '('), but how about the I I I. I need to detect if the Uppercase letters are 1 char long.
I think that this should be really easy to do with Regex but I don't know how to do it. Thanks in advance!
For your specific test cases this seems to work:
function camelCaseToString(str){
var a = str.replace( /([^A-Z( ]+)([A-Z(])/g, "$1 $2" );
var b = a.charAt(0).toUpperCase() + a.slice(1);
return b;
}
You can do it with:
str.replace( /(\(?[A-Z][A-Za-z])/g, " $1" );
A more generic approach will be to match cases when there is a lowercase letter followed with an uppercase one (([a-z])([A-Z])) or (|) when there is start of string position or a non-word char before a lowercase char (\b([a-z])):
function camelCaseToString(str){
var rx = /([a-z])([A-Z])|\b([a-z])/g;
var a = str.replace(rx, function($0, $1, $2, $3, $4) {
return $1 ? $1 + " " + $2 : $3.charAt(0).toUpperCase() + $3.slice(1);
} );
return a;
}
console.log(camelCaseToString('exampleText'));
console.log(camelCaseToString('ExampleText'));
console.log(camelCaseToString('string(parenthesis)'));
console.log(camelCaseToString('string (Parenthesis)'));
console.log(camelCaseToString('exampleWithRomanNumbersIII'));
The match is passed to the replace callback method, and if Group 1 matched, the space is inserted between the lowercase letter ($1) and the uppercase one ($2) (see $1 ? $1 + " " + $2) and when Group 1 did not match (meaning Group 3 matched, a lowercase ASCII letter after a word boundary), the first letter is turned uppercase (see : $3.charAt(0).toUpperCase() + $3.slice(1)).

Escape double quotes within double quotes with Regex[JS]

I have a JSON string: '{"place": {"address": "Main Street, \"The House\""}}'.
Before parsing it with JSON.parse() I have to make sure that the double quotes within double quotes are escaped properly.
I was trying to come up with the regex that would match "The House", but failed to so.
Any idea on how can I achieve desired result?
This would be possible with the help of positive lookahead assertion.
var s = '{"place": {"address": "Main Street, "The House""}}';
alert(s.replace(/"((?:"[^"]*"|[^"])*?)"(?=[:}])/g, function(m,group)
{
return '"' + group.replace(/"/g, '\\"') + '"'
}))
OR
var s = '{"place": {"address": "Main Street, "The House"", "country": "United Kingdom"}}';
alert(s.replace(/"((?:"[^"]*"|[^"])*?)"(?=[:},])(?=(?:"[^"]*"|[^"])*$)/gm, function(m,group)
{
return '"' + group.replace(/"/g, '\\"') + '"'
}))

How can I pattern match against exactly spaced names ?

How can I write a pattern for a name which can only include letters separated by single spaces if required? If there are multiple names, then they must be separated with a single space.
For example,
"Jane Doe" and "Jane" are correct but, " Jane" or "Jane " or "Jane Doe" are all incorrect.
My pattern,
/^([A-za-z]+ ?[A-za-z]+){1}$/
If i've understand you correctly, try this:
/^[A-Za-z]+(\s[A-Za-z]+)?$/
Your regular expression is not checking the full capital letter range (A-z must be A-Z)
NOTE: This is on the assumption that your question contains a typo and that in fact " Jane Doe" or "Jane Doe " is incorrect.
var patt=new RegExp(/^([A-Za-z]+ ?[A-Za-z]+){1}$/);
document.write(patt.test(" Jane Doe") + '<br/>'); --false
document.write(patt.test("Jane Doe") + '<br/>'); --true
document.write(patt.test(" Jane") + '<br/>'); -- false
document.write(patt.test("Doe ") + '<br/>'); -- false
document.write(patt.test("Doe") + '<br/>'); -- true
See fiddle: http://jsfiddle.net/FEycT/4/

Categories

Resources