Olena Horal Olena Horal - 1 year ago 106
Javascript Question

Regex for Mr. and Mrs. replacement

I need a regex to replace the First part of the string (Mr. or Ms. - ) e.g. "Mr. some name" or "Ms. some name" with their full equivalents. so that "Mr. some name" becomes "Mister some name" and "Miss some name". I can do that separately for each case like that:

function fn(str) {
if (/^Mr./.test(str)) {
return str.replace(/^Mr./, "Mister");
else if (/^Ms./.test(str)) {
return str.replace(/^Ms./, "Miss");

console.log(fn("Ms. Name")) // will output "Miss Name"

But I have a feeling that it should have "one string" solution.

Answer Source

Use "^Mr\." as your regex.

. without escaping matches every character.

And a for one line:

str = str.replace("^Mr\.", "Mister").replace("^Ms\.", "Miss");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download