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

Troubles encountered when populating the array within a Vue component

I am experiencing an issue with my ProductCard component where the addItem method is not successfully adding a new item to the array. <template> <div class="card"> <div v-for="item in TodoItems" :key="item.id ...

Creating a stacked chart in Angular using chart.js with JSON array of objects values

I am currently working on implementing a stacked chart using chart.js, and I have encountered some challenges: I am struggling to display currency values in the correct format on the chart (the height of the bar is not visible when passing amounts). How c ...

`My jquery mobile application fails to trigger the pageinit or ready events`

My website consists of 3 PHP pages: one index page and two subpages for sales and products. The index page has links to these subpages. When I click on the sales link, it is supposed to load sales data either on pageinit or document ready. However, no code ...

Obtaining a specific item from a group using AngularJS. Utilizing a declarative method

Consider a scenario where you need to apply a CSS rule to a specific element within a collection that needs to be selected. <div ng-repeat="fragments" ng-click="makeSelected()"></div> $scope.fragments = [ {id: 6379, someProperty: "someValu ...

Interactive mobile navigation featuring clickable elements within dropdown menus

I recently implemented a mobile nav menu based on instructions from a YouTube tutorial that I found here. Everything was working perfectly until I encountered an issue on the 'reviews list' page. The dropdown in the mobile nav is supposed to be ...

Tips on successfully transferring a JavaScript variable from PHP to JavaScript

I am struggling with how to manipulate a JavaScript variable in my HTML script and then pass it to a PHP file for incrementing by 1. However, I am unsure of how to return this modified variable back to the HTML file for display. Additionally, I am uncertai ...

Building an Angular form that is reactive and dynamically populates fields from an array

I am currently working with Angular 9 and I am facing a challenge in implementing a component that utilizes reactive forms. Below is a snippet of my code: approval-edit.component.ts public nominationAllOf: NominationAllOf[]; public approvalEditForm: Form ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Functionality of setExtremes ceases to function post initial loading

Initially, the setExtremes function works fine for the chart. However, when I switch pages or reopen the chart with a new JSON file, the setExtremes function stops working and fails to update the min and max values. Any idea why this could be happening? yA ...

Issue: The module 'xdl' cannot be located while executing the command "npm start" in React Native

Recently, I delved into learning React Native through an online Udemy course. Everything was going smoothly until a few days back when I encountered an error message after running the simple "npm start" command. Despite trying various solutions like reinst ...

What is the best way to loop through an API response in Vue.js?

Hey there, I'm new to Vue and struggling with iterating through data in my template. Despite being able to log everything properly, I can't seem to render it on the page. Here's the API URL: https://private-922d75-recruitmenttechnicaltest.a ...

typescript tips for incorporating nested types in inheritance

I currently have a specific data structure. type Deposit { num1: number; num2: number; } type Nice { num: number; deposit: Deposit; } As of now, I am using the Nice type, but I wish to enhance it by adding more fields to its deposit. Ultima ...

Learn the steps to invoke a JavaScript function from a <td> element within an ng-repeat loop

How can I call an Angular function inside ng-repeat td and replace the value from the function with the value in the td element? The code snippet provided below is not functioning as expected. Instead of getting the date, the same getCSTDateTime function i ...

Using JavaScript to place a particular tag at a designated position

I have a string that looks like this: var txtstr='<p>Text 1</p><p>&nbsp;</p><p>Text &nbsp;2</p><p>&nbsp;</p><p>Text 3&nbsp;</p>'; I have an <img src=..../> tag and ...

A guide to troubleshooting the "Cannot resolve all parameters error" in Angular

Recently delved into the world of angular 2, and I've come across my first challenge. I'm trying to establish a service for retrieving data from a server but I keep encountering this particular error Error: Can't resolve all parameters fo ...

Master the art of utilizing angular-filter

Encountering some challenges while attempting to utilize angular-filter: The following links have been imported into the HTML file: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> <script src=" ...

Leveraging properties in computed Vue.js

I have a computed property that looks like this: display() { return this.labs.map(function(x, i) { return [x, this.plotDt[i]]; }); } This property receives data as props: props: ["plotDt", "labs"], Both plotDt and labs are ar ...

Styling components using classes in Material-UI

I recently started using material-ui and noticed that it applies inline styles to each component. After running a test with multiple instances of the same component, I realized that there was no CSS-based styling - only repeated inline styles were generate ...

Is it possible to load a JavaScript file from a different domain using a bookmarklet?

I'm a newcomer to bookmarklets and I am experimenting with loading a JavaScript file from my own server/domain using the following bookmarklet/javascript code: javascript:(function(){s=document.createElement('script'); s.type=' ...

Tips on keeping Bootstrap Modals out of your browsing history

Imagine this scenario A visitor lands on Page A, clicks through to Page B, and then engages with a link that triggers a modal (code provided below) <a href="mycontent.html" data-target="#modal_xl" data-toggle="modal" data-backdrop="static">Click me ...