Is there a period, question mark, apostrophe, or space in the input string?

Currently, I am in the process of developing a program that can determine if an input string includes a period, question mark, colon, or space. If these punctuation marks are not present, the program will return "false". However, if any of them are found, the program will output all characters before the first instance of the punctuation. For example, given the string "grey cat", the program should return "grey" because it encountered a space. Is it possible to use logical OR operators in Javascript? I would prefer a solution without utilizing built-in functions, and efficiency is not a priority.

Update: The current version of the program is only displaying the original string. How can I modify it to print only the characters that appear before any punctuation?

function find_punctuation(str){
   let result = "";
   for (let i = 0; i < str.length; i++ ){
      if (str[i] === "." || str[i] === "?" || str[i] === "" || str[i] === ","){
         break;
      } else {
         result += str[i];
      }
   }

   return result;
}
console.log(find_punctuation('he. y'));

Answer №1

function extract_text_before_punctuation(str) {
  let result = "";

  for (let i = 0; i < str.length; i++) {
    // Check if the current character is a punctuation mark.
    const is_punctuation = (
      str[i] === "." ||
      str[i] === "?" ||
      str[i] === " " ||
      str[i] === ","
    );

    if (is_punctuation) {
      // If it's a punctuation mark, stop and return the text before it.
      break;
    } else {
      // If not a punctuation mark, add the character to the result string.
      result += str[i];
    }
  }

  // The result string now contains all characters until the first punctuation mark.
  // The loop stops as soon as it encounters any punctuation mark in the input string.
  return result;
}

console.log(extract_text_before_punctuation('he. y'));
console.log(extract_text_before_punctuation('hell,o'));
console.log(extract_text_before_punctuation('hello'));
console.log(extract_text_before_punctuation('cat?erpillar'));
console.log(extract_text_before_punctuation('grey cat'));

Answer №2

To extract text before punctuation marks, consider using a regular expression:

function extract_text_before_punctuation(str) {
  let result = str.match(/^(.*?)[.?: ]/);
  if (result) {
    return result[1];
  } else {
    return false;
  }
}
console.log(extract_text_before_punctuation('he.y'));
console.log(extract_text_before_punctuation('hey'));

Answer №3

Give this a shot:

function remove_punctuation(text){
   let cleanText = "";
   for (let j = 0; j < text.length; j ++ )
      if (text[j] === "." || text[j] === "?" || text[j] === "  ") break
      else cleanText += text[j]

   return cleanText
}
console.log(remove_punctuation('hi!'));

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

When the ENTER key is pressed, trigger a function within the form instead of submitting it

Incorporating a table with filterable data utilizing the jQuery DataTables library, I face an issue. The said table is situated within a form where selecting rows (via checkboxes in one column) prompts the SUBMIT button to add them to a collection. The ta ...

Tips for adjusting the search bar's position on a mobile device when it is activated by the user

I need help with an open source project where I am developing a search engine using Angular. When using smaller screen sizes, the search bar is positioned in the middle but gets hidden behind the keyboard terminal when clicked on. Can anyone advise on ho ...

Tips for inserting a footer at the bottom of every page during the conversion process from HTML to PDF

Could use some assistance with converting HTML into a PDF report. In particular, I want the footer to always appear at the bottom of the last page, even if there is minimal content on that page. Any suggestions? I've been utilizing the wkhtmltopdf to ...

What is the process for transitioning from Ajax to Fetch API in JavaScript?

Currently, I am utilizing the JavaScript version of RiveScript which relies on ajax, and I have decided to move away from using jQuery. There is a single line of ajax code that I need to update to integrate the new Fetch API. **Note: The ajax code can be ...

Tips for customizing the appearance of a label when a MUI Radio Button is selected

Hello everyone, I am attempting to customize the label text color of a radio button to turn blue when selected. https://i.stack.imgur.com/btSc2.jpg HERE IS THE CODE FOR MY MUI BUTTON SO FAR import * as React from "react"; import Radio from &quo ...

The Ajax request functions correctly in Chrome and Safari but encounters issues in Firefox and Internet Explorer

I've encountered an issue with jQuery where the call is failing when making a request with base64 authorization header in the beforeSend function. It's a simple request to retrieve projects. function GetProjects(full){ var query = "/Projects"; $ ...

Brick-themed HTML/CSS elements drift away from each other

I'm currently designing an image collage for my website and attempted to use masonry for the layout. However, when I adjust the size of the blocks, they seem to drift apart, creating large gaps between each block. Any suggestions on how to resolve thi ...

Having trouble retrieving information from the local API in React-Native

Currently, I have a web application built using React and an API developed in Laravel. Now, I am planning to create a mobile app that will also utilize the same API. However, I'm encountering an issue where I cannot fetch data due to receiving the err ...

Unable to locate a declaration file for the module "../constants/links" in src/constants/links.js, as it implicitly defaults to type 'any'

Within my VueJS application, I have brought in some constant variables. <script lang="ts"> import { Component, Prop, Vue } from 'vue-property-decorator' import { MOON_HOLDINGS_LINK, TWITTER_LINK } from '../constants/links' @Comp ...

The res.download() function in Express is failing to deliver the accurate URL to the client

When trying to utilize the res.download() method for downloading specific files from a server, there is an issue where triggering the res.download does not redirect the client to the correct URL. The files intended for download are located in a directory s ...

Tips for showing all percentages on a Google PieChart

I'm currently encountering two issues. How can I ensure that the entire legend is visible below the graph? Sometimes, when the legend is too large, three dots are added at the end. Another problem I am facing involves pie charts. Is there a way to d ...

Is there a way to load an image asynchronously when the page loads and show a loading gif during the loading process?

My image tag displays a dynamically generated graph from the database. The loading time can vary significantly, sometimes only taking a second while other times it may take up to 6 or 7 seconds for the graph image to appear. I am looking for a way to sho ...

Activate the function within the same class only for the selected item

Hello there, I'm struggling to grasp how to make this particular functionality work. Basically, I have 8 divs, each containing an image used as a button with the same class (tm-img), and hidden divs with additional information. My goal is to initiall ...

Update the text and background colors of all Vuetify components

Hey everyone, I'm trying to figure out how to change the text and background colors of all Vuetify components. I've tried using a custom theme but it's not working as expected. Any suggestions? :) const myCustomLightTheme = { dark: fals ...

Is there a way to incorporate a fade-in effect when I trigger the expand function in this script?

I recently came across a jQuery plugin for expanding and collapsing content. I am interested in adding a fade-in effect to this plugin specifically when the EXPAND button is clicked. How can I accomplish this? $(document).ready(function () { var maxlines ...

Merging two arrays together in JavaScript

Within my possession are two arrays: var g= [ { id: 36, name: 'AAA', goal: 'yes' }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { ...

Issue: Encounter an Error with Status Code 401 using Axios in React.js

For my login page, I am utilizing a combination of Laravel API and ReactJS frontend. In my ReactJS code, I am using Axios to handle the parsing of the username (email) and password. The login API endpoint is specified as http://127.0.0.1:8000/api/login, wh ...

Mocha retries causing logging malfunction: a problem to address

My current situation involves testing something on our network, and occasionally the network experiences delays causing the test to end prematurely. To address this issue, I attempted to set the test to retry with the command this.retries(1). While this ...

How to stop Accordion from automatically collapsing when clicking on AccordionDetails in Material-UI

I am working on a React web project with two identical menus. To achieve this, I created a component for the menu and rendered it twice in the App component. For the menu design, I opted to use the Material UI Accordion. However, I encountered an issue wh ...

Angular.js dynamically changing ng-class based on long-polling updates to a monitored variable

Currently utilizing angular.js for my project. I am implementing long polling with a server and would like to dynamically update an element in the view, specifically one with a class of 'updated', whenever the value of build_tag is incremented. ...