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);
Related
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());
I have a sentences like below, I need to match db defined messages with user messages and return what exactly is not matching. While matching the sentences we have two conditions,
In place of xxx (defined in dbmsg), User can substitute and send anything ( 0- 5 ) chars limit or may not send any value. For example, user can send this "Hi, Stay calm Thanks" which is valid. ( Because for first 2 xxx xxx they didnt pass anything and for last xxx they have substituted calm ( 0- 5) which is valid )
Other portion of the sentence should be exactly matching.
I have a regular expression,
let dbmsg = "Hi xxx xxx, Stay xxx Thanks"
let usermsg = "Hi qyz, Stay calm Thank you"
let Stat = "ok"
dbmsg = dbmsg.replace(/\s*(\xxx(?:\s*\xxx)*)/gi, (x, y) =>
'.{0,' + ((y.match(/\xxx/gi) || ['']).length * 5 + (y.match(/\s/g) || '').length) + '}')
//Substituting xxx with .{0,5} where in place of xxx user can send up to max 5 //characters(any)
dbmsg= dbmsg.replace(/[ ]/g, '');
usermsg = usermsg.replace(/[ ]/g, '');
let regex = RegExp("^" + dbmsg+ "$", "i");
if (!regex.test(usermsg)) {
Stat = "Notok"
}
Here we need to find out what is causing the failure, in case of error. In the above defined sentences, we should identify which of the following
1) xxx portion is not matching
2) Other portion of the sentence is not matching
I have tried the following in case of regular expression doesn't match,
Like in place of xxx, there can be any number of characters ( .* ) and if both the sentences still doesnt match, there seems to be a problem with other portion of the sentence.
dbmsg = dbmsg.replace(/xxx/gi, ".*");
let regex2 = RegExp("^" + dbmsg+ "$", "i");
if (!regex2.test(usermsg)) {
Status = "Other portion of the sentence is not matching"
}
else{
Status = "xxx portion is not matching"
}
From the given sentences dbmsg and usermsg only Thanks and Thank you are not matching ( Other portion is not matching)
The above method is working but its cpu utilization is more and it hangs the further requests. I suspect its because we are substituting .* . Is there any other approach which would consume minimal cpu time. Kindly help me on this?
How can I capture a word just after specific word in regex, I have to select everything between from - to and after to so there will be two capturing groups.
Example:
"From London to Saint Petersburg" I wanted to extract London Saint Petersburg from above string.
Im stuck with this code here, my current regex selecting to Saint Petersburg i wanted to get rid word from and to from the selection.
/(?=to)(.*)/i
You can capture the two groups you need and then use match to extract them:
s = "From London to Saint Petersburg"
console.log(
s.match(/From (.*?) to (.*)/).slice(1,3)
)
you can just use split() and use /From | to /, it will return an array containing split values
var str = "From London to Saint Petersburg";
var arr = str.split(/from | to /ig);
console.log(arr);
Here is sample code doing what you asks for:
<html>
<head>
</head>
<body>
</body>
<script>
var strIn = "From London to Saint Petersburg";
var regEx = /^From\s(.+?)\sto\s(.+?)$/;
var arrResult = regEx.exec(strIn);
var strOut = "Original:" + strIn + "<br>Result:<br>";
strOut += "1. " + arrResult[1] + "<br>";
strOut += "2. " + arrResult[2];
document.write(strOut);
</script>
</html>
Place this in a document. Open it with a browser. Here is how the result looks like:
Original:From London to Saint Petersburg
Result:
1. London
2. Saint Petersburg
Hope it helps!
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
I have a string like this:
Franciscan St. Francis Health - Indianapolis
I need to extract everything after '-' including the dash itself and output it in the second line..How do I extract everything before '-'?? Regex or jquery?
The string infront of '-' will be dynamic and could have varying number of letters...
Neither. I would just use the native .split() function for strings:
var myString = 'Franciscan St. Francis Health - Indianapolis';
var stringArray = myString.split('-');
//at this point stringArray equals: ['Franciscan St. Francis Health ', ' Indianapolis']
Once you've crated the stringArray variable, you can output the original string's pieces in whatever way you want, for example:
alert('-' + stringArray[1]); //alerts "- Indianapolis"
Edit
To address a commenter's follow-up question: "What if the string after the hyphen has another hyphen in it"?
In that case, you could do something like this:
var myString = 'Franciscan St. Francis Health - Indianapolis - IN';
var stringArray = myString.split('-');
//at this point stringArray equals: ['Franciscan St. Francis Health ', ' Indianapolis ', ' IN']
alert('-' + stringArray.slice(1).join('-')); //alerts "- Indianapolis - IN"
Both .slice() and .join() are native Array methods in JS, and join() is the opposite of the .split() method used earlier.
Regex or jquery?
False dichotomy. Use String.splitMDN
var tokens = 'Franciscan St. Francis Health - Indianapolis'.split('-');
var s = tokens.slice(1).join('-'); // account for '-'s in city name
alert('-' + s);
DEMO
join()MDN
slice()MDN
Probably no need for regex or jquery. This should do it:
var arr = 'Franciscan St. Francis Health - Wilkes-Barre'.split('-');
var firstLine = arr[0]
var secondLine = arr.slice(1).join('-');
Ideally, your data would be stored in two separate fields, so you don't have to worry about splitting strings for display.