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

Utilizing NextJS Image Component in Conjunction with Auth0

I have been working on integrating auth0 with nextJS and encountered an issue with the next.js Image component. Let's review the code snippet: import Image from "next/image" import { useUser } from "@auth0/nextjs-auth0" export def ...

Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of my code in AngularJS: var deferred = $q.defer(), frame = document.createElement('newFrame ...

Using an npm package in client-side JavaScript

I've been exploring client-side GitHub packages recently and came across developers mentioning that the packages can be downloaded using npm. This confuses me as I thought these were client-side JavaScript packages. They also mentioned something about ...

Ways to confine the tabindex within a specific div container

I am currently working on identifying examples of bad accessibility practices. Specifically, I am focusing on issues related to Keyboard Focus. The first example I have encountered is the lack of visibility when trying to navigate through a set of buttons. ...

Problem with Gulp-Watch Functionality on Windows 7 - Node.js, NPM, and Gulp All Up and Running Fine

As someone who is new to the world of Node.js, NPM, and other modern tools designed to improve productivity and workflow, I find myself faced with some challenges. Below are the specifications: Node version - v8.10.0 Gulp CLI version - 2.0.1 Gulp Loca ...

using jquery to retrieve the current time and compare it

This is the code I currently have: var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() aler ...

Configuring IP Whitelisting for Firebase Cloud Functions with MongoDB Cluster

What is the process for including my Firebase Cloud Functions in the IP whitelist of my MongoDB cluster? Error Message: ...

tips for setting the value of a checkbox to true in React Material-UI with the help of React Hooks

<FormControlLabel onChange={handleCurrentProjectChange} value="end" control={<Checkbox style={{ color: "#C8102E" }} />} label={ <Typography style={{ fontSize: 15 }}> C ...

bindings and validation of input values in angularjs

In my scenario, I am dealing with a dynamic regExp and unique masks for each input. For instance, the regExp is defined as [0-9]{9,9} and the corresponding mask is XXX-XX-XX-XX. However, when it comes to Angular's pattern validation, this setup is con ...

Enhance Material UI with custom properties

Is it possible to add custom props to a Material UI component? I am looking to include additional props beyond what is provided by the API for a specific component. For example, when using Link: https://material-ui.com/api/link/ According to the document ...

Protractor functions perfectly on localhost, but encounters a Timeout error when used remotely - the asynchronous callback was not executed within the specified timeout period

Running protractor protractor.conf.js --baseUrl=http://localhost:4200/ executes successfully by filling data, validating elements, etc. However, when attempting to test the same website through a remote URL protractor protractor.conf.js --baseUrl=http://t ...

Incorporating Bootstrap JS into Next.js

Currently, I am in the process of learning next.js and experimenting with incorporating Bootstrap into my projects. To begin, I initiated a new project using npx create-next-app@latest my-app, utilizing the newly created "app" directory structure. Follow ...

Step-by-step guide on validating a user in Joomla using AJAX and jQuery

Is there a way to authenticate a user in Joomla through an AJAX call? I want to implement an error effect if the login is incorrect and redirect the user upon successful authentication. I am specifically interested in using JQuery's .ajax API for thi ...

Entering a value into an HTML textbox using Awesomium in VB.NET

This code snippet is used to split text from a listbox: For Each Item As Object In ListBox1.SelectedItems TextBox2.AppendText(Item.ToString + Environment.NewLine) Next Dim str As String = TextBox2.Text D ...

What is the name of the scrolling header effect achieved in the following?

I've been seeing a lot of people using a unique header effect lately and I'm curious to learn more about how it's done. Can anyone explain the process behind achieving this effect, what it's called, and if there are any good tutorials a ...

Is there a way to remove text from a div when the div width is reduced to 0?

Upon loading the page, my menu is initially set to a width of 0px. When an icon is clicked, a jQuery script smoothly animates the menu's width to fill the entire viewport, displaying all menu items (links) perfectly. The issue I'm facing is that ...

The iframe is displaying a MIME warning for pdfmake: Resource being interpreted as a Document but transferred with MIME type application/pdf

We are developing a single-page application using Vue.js. Our goal is to generate a PDF on the client side, and we have chosen pdfMake from npm for this purpose. As per the documentation, to display the generated PDF within an <iframe>, you can simp ...

The div is incorrect and causing the label and input to move in the wrong direction

Whenever I try to adjust the position of the current-grade-name-input, the entire grade-point-input moves along with it inexplicably. /* final grade calculator: (wanted-grade - (current-grade * (1 - final%))) / final% Ex: have a 80 an ...

Retrieving a specific Project ID from Asana Task API using Node.js and parsing the JSON response

Utilizing the Asana Task API, we have the capability to retrieve a task's associated projects along with their GID and Notes (description text). The main objective Our aim is to extract the GID of the project containing #websiteprojecttemplate in its ...

Integrating React js with Layout.cshtml: Mastering the Fusion of React Routing and ASP.NET MVC Routing

My current project involves an ASP.NET MVC core application with the View written in cshtml. The routing follows the conventional asp.net mvc routing pattern. However, I've recently implemented a new module using React JS. Now, I'm faced with the ...