Ensure that a string contains only one instance of a specific substring

I need a function that removes all instances of a specific substring from a string, except for the first one. For example:

function keepFirst(str, substr) { ... }
keepFirst("This $ is some text $.", "$");

The expected result should be: This $ is some text .

I could achieve this by using split() followed by a for(){} loop, but I'm wondering if there's a more elegant solution available.

Answer №1

Here is a concise and efficient code snippet that utilizes the power of destructuring assignment.

function extractFirstString(str, target) {
  const [
    firstVal,
    ...remaining
  ] = str.split(target);

  return firstVal + (remaining.length
    ? target + remaining.join("")
    : "");
}

Answer №2

This code snippet helps in identifying the position of the first instance of a specified character and then removes all subsequent occurrences of that character.

console.log(keepFirst("This $ is some text $$ with $ signs.", "$"));
function keepFirst(str, rep) {
  var fInd = str.indexOf(rep);
  var first = str.substring(0, fInd + rep.length);
  var rest = str.substring(fInd + rep.length);
  return first + rest.replace(
    new RegExp(rep.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), 'g'), 
    '');
}

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 a class function within the static method `getDerivatedPropsFromState`

I've been updating the deprecated life-cycle method componentWillRecieveProps() to its new replacement static getDerivatedPropsFromState(). The issue I'm encountering with this update is that componentWillRecieveProps() uses a class function int ...

JavaScript code that uses jQuery does not function properly on an HTML form

Hello everyone, I am having trouble with some JavaScript code. Here is what I have: $(document).ready(function(){ $(".replyLink").click(function(){ $("#form-to-"+this.id).html(htmlForm()).toggle(500); return false; }); function htmlForm(){ var htm ...

Connect radio input's value to object's key within AngularJS

Within my controller, I currently have an object structured as follows: $scope.colors = { green: "Green", yellow: "Yellow", red: "Red" }; I am attempting to dynamically generate radio inputs and then link the input value to the corresponding ...

What is the reasoning behind the return type of void for Window.open()?

There is a difference in functionality between javascript and GWT in this scenario: var newWindow = window.open(...) In GWT (specifically version 1.5, not sure about later versions), the equivalent code does not work: Window window = Window.open("", "", ...

Learn how to utilize Vue 3 to access properties that have been passed down from a parent component, even if they

Hey there, hope everything is going well. I'm familiar with react.js, but when I gave vue a try, things felt a bit different. In react, it's easy to access props passed from the parent in the child component without much hassle. However, in vue, ...

Using Vue.js to bind labels and radio buttons in a form

My goal is to generate a dynamic list of form polls based on the data. However, using :for or v-bind:for does not result in any HTML markup appearing in the browser, causing the labels to not select the corresponding input when clicked. I have prepared a J ...

Looking for an uncomplicated SSO system similar to Google Identity Toolkit but with a customizable UI interface?

I'm really impressed with the Google Identity Toolkit, it's so user-friendly and easy to set up! However, I'm having trouble with the fact that it forces me to use its UI. Is there another option available that will allow visitors to simply ...

Is it feasible to send props to { children } within a React functional component?

Workaround presented below. I am attempting to send props down to a child component using {children}. The Parent component: const ParentComp = ({ children, propsToSendToChild }) => ( <div>Dynamic component content: {children} &l ...

Having trouble importing a file in TypeScript?

I needed to utilize a typescript function from another file, but I encountered an issue: I created a file called Module.ts with the following code snippet: export function CustomDirective(): ng.IDirective { var directive: ng.IDirective = <ng.IDire ...

The deletion of Webpack Clean- /public/js has been successfully completed

I am utilizing the clean-webpack-plugin to empty the contents of my public/js directory. https://www.npmjs.com/package/clean-webpack-plugin Despite trying various methods, I keep encountering the message /public/js has been removed plugins: [ new CleanW ...

What is the best way to use checkboxes in VueJS to apply filters on a loop and display specific results?

I'm struggling with implementing filters using checkboxes on a list of results and could really use some assistance. Currently, only the 'All' option is working for applying any filtering logic. Here is how my HTML looks like with the filt ...

Creating an HTML slideshow banner: What you need to know

I am looking to create a slideshow for my banner that changes automatically. The banners are located in a folder, and I want the website to display them one by one without manual intervention. Currently, I have managed to display the images from the folder ...

Issue with remounting in Nextjs 13

import { useRouter, useSearchParams, usePathname } from 'next/navigation'; export function useQueryParams() { const pathname = usePathname(); const router = useRouter(); const searchParams = useSearchParams()!; const updateQu ...

Creating a unique custom view in React Big Calendar with TypeScript

I'm struggling to create a custom view with the React Big Calendar library. Each time I try to incorporate a calendar component like Timegrid into my custom Week component, I run into an error that says react_devtools_backend.js:2560 Warning: React.cr ...

The onSubmit event handler seems to be malfunctioning within a Reactjs form

I recently started using React and encountered an issue with my form: class CustomForm extends React.Component { handleFormSubmit = (e) => { e.preventDefault(); const title = e.target.elements.title.value; const content = e ...

Tips for center-aligning layouts in Angular Material

I am struggling with the Angular Material flex layout, so I took this directly from the Angular Material website. Based on the documentation for layout container, items are arranged in a row with a max-height of 100% and max-width matching the width of th ...

"Utilizing Promises in AngularJS Factories for Synchronous API Calls

Attempting to implement synchronous calls using a factory pattern. $scope.doLogin = function (username, password, rememberme) { appKeyService.makeCall().then(function (data) { // data = JSON.stringify(data); debugAlert("logi ...

Implementing Icons in Custom Headers of AG Grid Using vue js

I am working on implementing a new feature in AG Grid where I want to display an info icon in the header along with a tooltip that appears when the icon is hovered over. I have already created a custom tooltip component that works correctly, but once I a ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

What is the best way to modify the glyphicon within the anchor tag of my AJAX render property?

Consider the use of Ajax: "target 0" with a render option for an anchor tag. Initially, I am utilizing the class "glyphicon glyphicon-chevron-right". Now, I wish to change it to "glyphicon glyphicon-chevron-down" when clicked. $(document).ready(funct ...