JavaScript conditional substring manipulation

I am working on a function that is designed to clean strings, specifically two types of strings:

"SATISFACTION._IS1.TOUTES_SITUATIONS.current_month_note"
and
"SATISFACTION._IS1.TOUTES_SITUATIONS.note"
.

PS Just to clarify, TOUTES_SITUATIONS is a variable.

What I need to extract from these strings is "TOUTES_SITUATIONS"

Below is the code snippet I have:

const extractSituation: Function = (sentence: string): string => {
    return sentence.substring(
        sentence.lastIndexOf('1.') + 2,
        sentence.lastIndexOf('.n'),
    );
};

Currently, this code only works for the string

"SATISFACTION._IS1.TOUTES_SITUATIONS.note"
but not
"SATISFACTION._IS1.TOUTES_SITUATIONS.current_month_note"

Can you suggest a way to handle both types of strings effectively?

Answer №1

Remember, arrays in programming languages typically start at an index of 0. Here's an example of how you can extract a specific part of a sentence:

const getSegment: Function = (text: string): string => {
    return text.split('.')[2];
};

Answer №2

If you're looking to extract the text between the first instance of SATISFACTION._IS1. and the last ., a regex could do the trick:

let str1 = "SATISFACTION._IS1.TOUTES_SITUATIONS.current_month_note" 
let str2 = "SATISFACTION._IS1.TOUTES_someother.text__SITUATIONS.note" 

let regex = /^SATISFACTION._IS1\.(.*)\..*$/
console.log(str1.match(regex)[1])
console.log(str2.match(regex)[1])

Answer №3

My understanding is:

1) In the scenario, any kind of string can be considered.

2) The 'situation' is separated by periods.

To extract the specific part of the text containing the 'situation', you can locate the beginning of the situation in the sentence, and then find the next period to isolate the 'situation' substring.

const extractSituation: Function = (sentence: string): string => {
    // Finding the start of the situation in the sentence
    var situation = sentence.substring(sentence.lastIndexOf('1.') + 2);

    // Locating the end of the situation
    return situation.substring(0, situation.indexOf('.'));
};

This method is applicable as long as each 'situation' is always introduced by the '1.' marker.

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

Transform a text string into JSON format using Javascript

I need help converting a text string to JSON format using JavaScript. The text string is as follows: workingtable;AB8C;book_id;7541; I want to convert it into JSON format like this: {"workingtable":"AB8C","book_id":"7541"} Is there a specific JSON funct ...

Is all of the app fetched by Next.js when the initial request is sent?

After doing some research online, I learned that Next.js utilizes client-side routing. This means that when you make the first request, all pages are fetched from the server. Subsequent requests will render those pages in the browser without needing to com ...

Notes on using touch devices with Angular

My goal is to make my Angular application capable of displaying a footnote on mobile devices when text injected with nativeElement.innerHTML is clicked. I attempted to explain this before but feel that I didn't do it justice, so here's another sh ...

Incorporate socket.io into multiple modules by requiring the same instance throughout

I am feeling a bit lost when it comes to handling modules in Node.js. Here's my situation: I have created a server in one large file, utilizing Socket.io for real-time communication. Now, as my index.js has grown quite big, I want to break down the ...

Having trouble displaying a cube using three.js even though I have meticulously organized the object-oriented structure of my application

Creating a cube or any other geometric figure with three.js can be crystal clear when your code is simple. However, when trying to incorporate module logic in an OO-style structure for your application, you might encounter some challenges. I have faced sim ...

A guide on accessing JavaScript files from the components directory in a React Native iOS application

I am encountering difficulty in accessing the components folder within my React Native Project on IOS. The error message I am receiving is: Unable to resolve module ./Login from ....../ReactNative/ReactNativeProject/components/App.js: Unable to find ...

Ways to create distinct identifiers within a recurring function:

I am using this function twice: function (data) { $.each(data.items, function(i,item) { var $items = $('<div class="col-sm-4 grid-item"><div class="thumbnail"><input type="checkbox" name="thing_'+i+'" ...

Mastering the utilization of componentDidMount and componentDidUpdate within React.js: a comprehensive guide

I am facing an issue. I need to find an index based on a URL. All the relevant information is passed to the components correctly, but I encounter an error after loading: Cannot read property 'indexOf' of undefined The JSON data is being transmi ...

Populate a div using an HTML file with the help of AJAX

In my main HTML file, there is a div element: <div id="content"></div> Additionally, I have two other HTML files: login.html and signup.html. Furthermore, there is a navigation bar located at the top of the page. I am curious to know if it i ...

Executing jQuery AJAX with PHP using 'POST' method to receive and process PHP code

Something seems to have gone wrong with my setup; it was functioning properly before but is now encountering issues. When trying to make a POST call from an HTML file to a php file (which fetches data from a REST API), instead of receiving the expected API ...

Maintaining hover effects even when elements are not in view

I am facing an issue with my absolutely positioned <div> (which serves as a menu) located in the corner of a webpage. The problem arises when I try to animate it on hover, but as soon as the cursor moves beyond the viewport, the hover action stops. I ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

Transforming a canvas element into an image sans the use of toDataURL or toBlob

Recently, I developed a small tool which involves adding a canvas element to the DOM. Strangely, when trying to use toBlob or toDataURL, I encountered an issue with the canvas being tainted and received the error message (specifically in chromium): Uncaugh ...

Error in linking PHP code to display stored tweets using HTML code

![enter image description here][1]![image of output of twitter_display.php][2] //htmlsearch.html file <!doctype html> <html> <head> <title>Twitter</title> <meta charset="utf-8"> <script> window.onload = function ...

Tips for Dynamically Binding Data in Angular ChartsWant to learn how to dynamically bind

I have integrated angular-charts directives into my application and everything works perfectly when initializing the data. However, I encountered an issue when reading the data from a JSON file and assigning it to the chart. The x-axis and y-axis are gener ...

Tips on implementing jQuery in a JavaScript file referenced in angular.json

Currently, I am utilizing a JavaScript file that incorporates jQuery within it. In order to employ this JavaScript file, I have included it in the scripts array within the angular.json file. Additionally, I have also included jQuery in the same array befor ...

Toggle textboxes using jQuery depending on the radio button choice

I'm trying to make specific textboxes appear when a particular radio button is clicked on my form, but I want them to remain hidden otherwise. Here's an example of what I've implemented: HTML: Radio buttons: <p>Show textboxes<inpu ...

Guide on how to send files to an API using a form in React with MUI

I am struggling with sending an image through the front-end to my back-end application that is set up to accept data. Here is the code I have: import { useState } from 'react'; import axios from '../../config'; import { useNavigate } fr ...

What is the recommended approach for effectively cascading the deletion of a secondary object in MongoDB when an account is

My app allows users to create accounts and interact with posts by liking and sharing them. However, I'm facing an issue when a user decides to delete their account. I have managed to resolve most of the related data removal except for one specific cas ...

After implementing two hooks with null properties, the code fails to execute

Recently, I encountered an issue with this section of the code after upgrading react scripts from version 2.0 to 5.0. const { user, dispatch } = useContext(AuthContext); const { data } = useFetch(`/contracts/${user.contractType}`); if (!user) { ...