Retain only N instances of a particular character within a JavaScript string

Suppose I have a string like this: "a_b_c_d_restofthestring" and I want to keep only 2 underscores. For example,

 "a_b_cdrestofthestring"
 "abc_d_restofthestring"

Both of these are valid outputs.

This is my current implementation:

let str = "___sdaj___osad$%^&*";

document.getElementById('input').innerText = str;

let u = 0;
str = str.split("").reduce((output, c) => {
  if (c == "_") u++;
  return u < 2 || c != "_" ? output + c : output;
});

document.getElementById('output').innerText = str;
<div id="input"></div>
<div id="output"></div>

I'm wondering if there's a more efficient way to achieve this...

Answer №1

Your code is running smoothly. However, here's a concise regular expression that removes all underscores except for the last two in the input string.

let input = "___sdaj___osad$%^&*";
let output = input.replace(/_(?=(.*_){2})/g, '');

console.log("input: " + input);
console.log("output: " + output);

This approach is not very versatile as you would need to tweak the regular expression whenever you want to replace a different character or allow more than 2 occurrences. Nevertheless, if you are comfortable with this limitation, this solution requires less code maintenance.


Update: Here is an improved version that is fully generic and should offer better performance:

let input = "___sdaj___osad$%^&*";

function replace(input, char = '_', max = 2, replaceWith = '') {
  let result = "";
  const len = input.length;
  
  for (let i = 0, u = 0; i < len; i++) {
    let c = input[i];
    result += (c === char && ++u > max) ? replaceWith : c;
  }
  
  return result;
}

console.log("input: ", input);
console.log("output: ", replace(input));

Check out this jsPerf analysis.

Answer №2

To transform a string, you can utilize a regular expression that identifies an underscore along with a counter to keep track of the underscores that need to be retained while replacing the rest.

var text = "a_b_c_d_restofthestring",
    result = text.replace(/_/g, (char => count => char && count-- ? '_' : '')(2));
    
console.log(result);

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

Delay the execution of a JavaScript function by a few seconds

<script type="text/javascript"> var timeout; function doAjaxFunc(){ alert("called"); $.ajax({ type: "POST", url: "searchSuggest.php", data: dataString, cache: fal ...

Guide on choosing a specific div element from a different page using AJAX

I have a Social Media platform with posts, and I am trying to display the newest ones using JavaScript (JS) and AJAX. I attempted to reload my page using AJAX and insert it into a div element, but now the entire website is loading within that div element, ...

How to retrieve a JSON value without a key using jQuery

I am struggling to fetch JSON using jQuery. If anyone can help me figure out the mistake in my code that would be greatly appreciated. The data.json file contains { "value1", "value2", "value3", "value4" } Here is my jQuery code $.getJSON( "data.js ...

Determine the distinct elements in an array using JavaScript/jQuery

I have incorporated Gridster widgets into my webpage, each with a button that turns the widget's color to red when clicked. Upon clicking the button, the parent element is also added to an array. My main goal I aim to have the parent element added t ...

Accept input from the user N times using the Node.js console

Hey there, I'm facing a challenge with getting user input in Node.js and running a function on each input a specified number of times. Unfortunately, using either a while or for loop doesn't seem to be the solution. Any suggestions or guidance w ...

Convert a JSON Object using AngularJs

Is there a method in Angular to restructure this JSON Object? I am looking to convert the JSON object from its original format: $scope.TestJson = { "filters": [ { "dataPropertyID": "VoidType", ...

Error TS2451 in GatsbyJS: "react_1" block-scoped variable cannot be redeclared

Trying to implement typescript with custom routes in gatsbyjs: require("source-map-support").install(); require("ts-node").register(); exports.createPages = require("./src/createPages"); tsconfig.json { "include": ["./src/**/*"], "compilerOptions": ...

Can the text glow in the navbar be toggled?

Hey everyone, I'm new here and I've been struggling to find a solution to my issue. I have a website with a navigation bar that toggles different divs to simulate changing pages within the same HTML file. The problem is, there is no visual indica ...

Dealing with numerous promises simultaneously using AngularJS Factory

I have created a code that makes multiple $http calls recursively and saves all the promises it returns in an array. Then, I resolve all of them and save the responses in another array. Now, my question is: How can I efficiently return this final array to ...

Modify a particular entry that is being looped through in PHP

Currently, I have coded the following: <div class="row"> <div class="col-lg-12"> <table id="usertable" class="table table-bordered table-hover text-center"> <thead> <th class="col-lg-1 text-center">User ID</th> ...

When the first element of an array is undefined, Angular's ngFor will not render anything

We have an array called stringArray: var stringArray = new Array(); stringArray[1] = 'one'; In Angular, the ngFor directive displays nothing when stringArray[0] is undefined. How can this issue be resolved? ...

My initial experience with vue.js has been complicated by issues with routers

I've recently dipped my toes into the world of Javascript and vue.js. After following a tutorial on creating a single page shopping application, I decided to incorporate routers into my learning project. However, I encountered some interesting error ...

Transferring information between postponed functions

Currently, I am incorporating deferred functions with .done and facing a situation like this: askTime(number).done(formatTime).done(function(html){ times += html; }); Despite the fact that formatTime returns data, the html variable contains the data r ...

Tips for connecting an input tag within a popover to a Vue Model

I've got an input nested inside a popover content as shown below: JSFiddle Link HTML code snippet: <div id="vue-app"> <div class="btn btn-primary" data-toggle="popover" data-placement="bottom" title="Hello World!" data-html="true" data ...

Creating an Add-in using the Excel JavaScript API based on an already existing spreadsheet

Is there a way to create an Add-in using Excel JavaScript API from an existing spreadsheet? When running npm start, it generates a blank workbook. I believe changes need to be made in the Manifest.xml file, as npm start triggers office-addin-debugging star ...

Can you choose and generate identical values using react-select?

I am working on implementing a multi Creatable feature where users can select a preset value or create a new value during the same interaction. To illustrate, here is my current render: import CreatableSelect from 'react-select/creatable'; functi ...

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

The sequencing of AJAX calls on the server side may not necessarily match the order in which they were initiated on the client side

I am working on an ASP.NET MVC application that includes a JavaScript function within a view. Here is the code snippet: function OnAmountChanged(s, fieldName, keyValue, url) { console.log("Get Number: " + s.GetNumber()); console.log(" "); ...

What are the steps to integrate mailjet into my Vue application?

I am looking to utilize mailjet for my contact form. I have installed it using "$ yarn add node-mailjet" and followed the steps provided. However, I am a bit confused about whether I am integrating mailjet correctly. Below is the code I am currently using: ...

Send pages to the holding page first before redirecting them to the appropriate page on the new website

I am in the process of updating my old website (www.old.com) with a new one that has similar pages (www.new.com). I want all the pages from www.old.com to automatically redirect to a temporary holding page (a basic html page with a countdown script and red ...