Utilize AngularJS to Capitalize the First Letter and the Letter Following a Dot (.)

I am seeking a solution to capitalize the first letter in a given string, like so:

 sumo => Sumo 

Additionally, I need to capitalize strings in the following format:

Dr.ravi kumar => Dr.Ravi kumar

Although I have implemented an Angular filter that successfully handles the first scenario, it does not work for the second one. Here is the custom filter that I am currently using:

 angular
    .module('app')
    .filter('capitalize', function () {
        return function (input, scope) {
            if (input != null) {
                input = input.toLowerCase();
                return input.substring(0, 1).toUpperCase() + input.substring(1);
            }
        }
    });

Answer №1

string="hello there. I am Dr.Test. Nice to meet you. By the way, what is your name?";
string=string.split("");
capsLock=true;
for(key in string){
 console.log(string[key],capsLock);
  if(string[key]==="."){
    capsLock=true;
  }else{
  if(capsLock&&(string[key]!==" ")){
    string[key]=string[key].toUpperCase();
    capsLock=false;
   }}}
  string=string.join("");
 console.log('result:',string);

My revised response (slower):

string="hello there. I am Dr.Test. Nice to meet you";
words=string.split(" ");
var dots=[0];
for(key in words){//loop through words
    var word=words[key];
    var chars=word.split("");
    if(dots.length){//there was a dot before, that wasn't a doctor: let's find the first letter and capitalize it
       chars[0]=chars[0].toUpperCase();   
       dots.shift();//remove dot      
    }
   chars.forEach((char,i)=>{if(char=="."){dots.push(i)}});
   if(dots[0]&&dots[0]!=chars.length-1){//dot not at the end...
       chars[dots[0]+1]=chars[dots[0]+1].toUpperCase();//capitalize our doctor...
       dots.shift();//remove dot from array
   }
   word=chars.join("");
   words[key]=word;
}
 string=words.join(" ");
 console.log('result:',string);

Working demo: http://jsbin.com/docecuvote/edit?console

Answer №2

Give this a shot:

angular
    .module('app')
    .filter('capitalizeFirstLetter', function () {
        return function (input, scope) {
            if (input != null) {
                input = input.toLowerCase();
                return input.substring(0, 1).toUpperCase() +input.substring(1).split('.')[0] + '.' + input.substring(1).split('.')[1].substring(0, 1).toUpperCase() + input.substring(1).split('.')[1].substring(1)
            }
        }
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the means to obtain the element where another element is dropped in ngDraggable within AngularJS

We are currently utilizing ngDraggable in AngularJS. Our goal is to retrieve the element on which another element is dropped. While we can obtain data of the drag element using ng-drag-data, we are facing difficulties in capturing data of the drop locati ...

Attempting to capture a previously unhandled error thrown by Axios when utilized in conjunction with React Query (with suspense mode enabled) within a NextJs application

Utilizing NextJS, React query (with axios and suspense mode), I am attempting to handle an intentional 404 error from my API. Although I successfully caught it in my error.js file, the same error still shows up in the console as "uncaught." https://i.stack ...

The HTML table seems to be inexplicably replicating defaultValue values

I'm encountering an issue where, when I use JavaScript to add a new table data cell (td), it ends up copying the defaultValue and innerText of the previous td in the new cell. This is confusing to me because I am simply adding a new HTML element that ...

Attempting to Create a New User and Display the Resulting Page Using JavaScript and Handlebars Templates

I've implemented a form that allows users to input data. Once the user hits "Add User", they are successfully added to the database. However, instead of transitioning to the next page as expected, the form remains populated on the current page. The h ...

Obtain a variety of selections for multiple selects and individually incorporate them into a standard select menu

Is there a way to select multiple options from a list and add them to another list without losing any selections? Currently, when I add two selected options, they combine into one in the target list. Check out this JSFIDDLE EXAMPLE for reference. Here is ...

Exploring the concept of generator functions in ES6

I'm grappling with understanding JS generators and why the asynchronous operations in the example below are returning undefined. I thought that using yield was supposed to wait for asynchronous calls to finish. function getUsers(){ var users; $.aj ...

Determine the exact moment at which the value shifts within the table

Looking for assistance in automating the grade calculation process whenever there is a change in table values. Any suggestions on how to achieve this? I am new to events and AJAX, so any help would be appreciated as I am still learning. Please see the ima ...

Issue with React Hook Form - frequent failure in submitting the form

I have implemented the useForm hook from https://www.npmjs.com/package/react-hook-form. However, I am encountering some inconsistent behavior where it sometimes works immediately, sometimes requires a page refresh to work, and sometimes doesn't work a ...

Executing a personalized function within a Server Component with the Next JS App Router while the application is running

In my server component Home, I call the function getMyAge: // app/page.tsx import { getMyAge } from './utils/datetime'; export default function Home() { return ( <Page> <Paragraph>I'm {getMyAge()} years old</Parag ...

What is the process for removing a key from an object and replacing it with its corresponding value?

My JSON sample looks like this: var obj={ "results":{ "grade":"A", "marks":12 }, "data":{ "name":"sam", "gender":"male", "age":10 } }; I am trying to transform the above JSON to: var obj={ "res ...

Discover the method of accessing items pushed into an empty array within a view

Is there a way to retrieve the pushed array in the view section? $scope.addCart = function(){ $scope.viewDetails=[]; $scope.viewDetails.push({"name":"mobile"}); $scope.viewDetails.push({"price":"23"}); ...

Issues encountered while trying to implement HTML text within span tags

In my code snippet, I am using a span element: <span> {textToRender} </span> The purpose of this code is to render HTML text (as a string) within a span element. some text <br/> some text <br/> some text <ol>text However, wh ...

Utilize AngularJs to transform base64 encoded data into an image

I am encountering an issue while attempting to convert base64 formatted data into an image using AngularJs. If anyone could provide assistance on how to resolve this error, I would greatly appreciate it. $http({ method: 'GET', ...

Is it possible to distinguish and identify each separate window when a user opens multiple instances of your site?

Has anyone explored the possibility of distinguishing between multiple windows a user may open on the same site? My goal is to assign the initial window the name "window1" and subsequent windows "window2" and so forth. Is there a method for achieving this ...

Troubleshooting Transclusion Problems in Angular

Is there a way to reference an array using i instead of # when using transclude in a repeat function? In the code below, my list is generated correctly with the right number of items from the array, but only returns data for x rows as specified in the mark ...

Issue with express-http-proxy where relative URL paths are not functioning as expected

My server is hosting an app along with a few simple web microservices. I want to access these services over the internet without having to open individual ports for each one. To achieve this, I decided to set up a reverse proxy on the server using express- ...

Encountering the error message "Module 'request' not found" despite the fact that I've already included the request module

I'm currently facing an issue with my Cloud Function that involves using the request library. After installing the request package using npm install request, I noticed it's located in the node_modules directory, just like all the other packages: ...

Is it possible to customize the color of the modal backdrop in layer v4 of the Material-UI library

I am struggling to modify the background color of an MUI V4 modal. Instead of getting a clean color, I am seeing a gray layer on top of the backdrop. Though this seems to be the default behavior, I want to remove it and target the shaded div directly rathe ...

The functionality of Angularjs ui-modal is being affected by issues related to the $http request

Currently, I am incorporating Angularjs 1.5.x along with AngularUI Bootstrap. My goal is to initiate a bootstrap modal and populate it with remote data by making use of $http request. To achieve this, I am utilizing the resolve method within the modal&ap ...

Achieving Compatibility Between jQuery 3.6.0 and Node.js v12.16.1

Utilizing an online IDE known as Replit, I am working on node.js projects running on the node version: 12.16.1. However, my current challenge lies in attempting to make jQuery 3.6.0 compatible with this particular node.js version. Despite trying various me ...