Moving punctuation from the beginning or middle of a string to the end: A guide

My Pig Latin converter works well with single or multi-word strings, but it struggles with punctuation marks.

For example, when I input translatePigLatin("Pig Latin.");, the output is 'Igpay Atin.lay' instead of 'Igpay Atinlay.'. How can I modify the function to handle this correctly?

This is the current function:

function translatePigLatin(string) {
  var arr = string.split(' ');
  var str;
  for (var i = 0; i < arr.length; i++) {
    var j = 0;
    if (!/[\d]/.test(arr[i])) {
      while (/[^aeiou]/i.test(arr[i][j])) {
        j++;
      }
      if (j > 0) {
        arr[i] = arr[i].slice(j) + arr[i].slice(0, j) + 'ay';
      } else {
        arr[i] = arr[i] + 'way';
      }
    }
    if (/[A-Z]/.test(arr[i])) {
      arr[i] = toTitleCase(arr[i]);
    }
  }
  return arr.join(' ');
}

function toTitleCase(str) {
  return str.replace(/\w\S*/g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });
}

Answer №1

If you want to modify your string by removing specific punctuation marks, you can try this function:

function removePunctuation(str)
{
  var punctuation = ".,!@#$";
  var matches = 0;
  for(var i=0;i<str.length-matches;i++)
  {
    if(punctuation.indexOf(str[i])!=-1)
    {
      str = str.substr(0,i) + str.substr(i+1)+str[i--];
      matches++;
    }
  }
  return str;
}

This function utilizes a for loop to iterate through the characters of your string. If it encounters a character that is in the punctuation string, it moves that character to the end of the string. So, for example, applying removePunctuation("Igpay Atin.lay") would result in "Igpay Atinlay.". Feel free to give it a try!

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

Encountered an error while executing findByIdAndRemove operation

Could someone please assist in identifying the issue with the mongoose findByIdAndRemove function in the delete route provided below? //DELETE Route app.delete("/blogs/:id", function(req, res){ //Delete blog Blog.findByIdAndRemove(req.params.id, funct ...

Tips for choosing all elements in a form that have a specific class assigned

I am attempting to target all fields in a form with a specific class name and then select all the remaining fields. This is my form: <form style="margin:20px 0" id="myform_2"> <p> Query Name : <input i ...

Add a luminous shine to a THREE.TextGeometry element within the Three.js environment

After conducting extensive research on Google, I am still trying to determine if it is possible to achieve a glow effect within the three.js environment. My goal is to create a glowing effect based on TextGeometry rather than a simple primitive shape like ...

Incorporating Functions from an External Script in ReactJS/GatsbyJS

One of the functionalities on my website involves dynamically inserting a script into the head when a form element is focused, enabling it to load faster. This process is achieved using basic vanilla JS rather than React Helmet, as shown below: const handl ...

Tab knockout binding

I have a section in my HTML with 2 tabs. The default tab is working properly, but when I attempt to switch to the other tab, I encounter an error. Can anyone provide assistance in determining why this error occurs? Here is the HTML code: <ul class="na ...

What is the best way to implement asynchronous guarding for users?

Seeking assistance with implementing async route guard. I have a service that handles user authentication: @Injectable() export class GlobalVarsService { private isAgreeOk = new BehaviorSubject(false); constructor() { }; getAgreeState(): Obser ...

Tips for managing unexpected TCP disconnects?

Using Node.js, I set up both a TCP server and an HTTP server. The TCP server was intended to connect with hardware devices via TCP connection. I have 100 TCP clients that are maintaining their connections with the server. Normally, when a TCP client disc ...

What are some methods to make sure that functions in AngularJS do not run at the same time

I am new to the world of JavaScript and I have encountered a problem with one of my functions. The function is designed to retrieve cached resources, but if the resource is not found in the cache, it makes a call to the back-end. The issue arises when thi ...

Executing a time-consuming function call within the componentDidMount lifecycle method of a React component

When working with my React component, I utilize the componentDidMount function to pass a string received through props to a processing function. This function then returns another string which is used to update the component's state. import React, { C ...

Finding the Perfect Placement for an Element in Relation to its Companion

Is there a way to achieve an effect similar to Position Relative in CSS using jQuery? I have developed a tooltip that I want to attach to various objects like textboxes, checkboxes, and other text elements. My code looks something like this: <input i ...

What is the best way to swap out every instance of an array?

There are two arrays that I'm working with, The first array is defined as var symbols = ['A', 'B'];, and the second array is defined as var num = ['3', 'A', '5', '4']; I am looking for a so ...

Error: The current element cannot be clicked. Please try again

I have been attempting to trigger a click event on another button within an onClick event function. An error occurred: Uncaught TypeError: this.clickBack.current.click is not a function The React version being used is 16.8.6 constructor(props) { s ...

Discovering elements that are currently visible in an Angular list

Suppose there is a variable named users which represents an array We have the following ng-repeat statement: ng-repeat="user in users | filterUser: searchUser: assignedUsers: selectedDivision" After filtering the users using searchUser and selectedDivis ...

How can you proactively rebuild or update a particular page before the scheduled ISR time interval in Next.js?

When using NextJS in production mode with Incremental Static Regeneration, I have set an auto revalidate interval of 604800 seconds (7 days). However, there may be a need to update a specific page before that time limit has passed. Is there a way to rebui ...

Unpredictable hovering actions when interacting with nested items within the hover layer

Imagine a scenario where we have the following elements: A container that holds everything A baseDiv inside that container // Let's create a base layer var container = document.getElementById('container') var baseDiv = document.createEl ...

Ending the Firefox browser using JavaScript

I have been trying to use the basic window close javascript command window.close(); but it seems to only work in IE and not in any other browser. Can anyone provide assistance on how to successfully close a browser tab in Firefox, Opera, or Chrome? Thanks ...

The operation of "grunt build" results in a Lexer Error, causing the ng-include

After deploying my unminified code successfully, I proceed to run grunt build and deploy from the dist folder. However, upon checking one of the pages, I encounter a breakage with an error in the console: Error: [$parse:lexerr] Lexer Error: Unexpected nex ...

I am attempting to access data through an ajax function, but it is not functioning correctly

When working with asp.net webform, I encountered an issue while trying to call data using an ajax call. Although a similar function on another page works without errors, on this particular page, I am facing an error. The error I am getting is pageCountInt ...

The functionality for PHP photo upload preview is currently not compatible with images taken with a mobile camera

In my responsive web app, users can upload photos. Everything works perfectly on desktop, but on mobile devices, there's a peculiar issue. When attempting to upload a photo by using the camera option, the preview doesn't show up unless an alert i ...

Ways to display the ping of a game server on your screen

Is there a way to display the game server's ping on the screen like in the example below? this.tfEnter.text = ShowPing + " ms"; Sometimes the code snippets provided in examples may not function properly. Channel List Image: https://i.stack ...