How can I write a JavaScript function that eliminates all white spaces within a string?

Exploring ways to create a custom function that trims white spaces from the beginning and end of a string (including \n, \t) without relying on built-in methods like trim(), replace(), split(), or join()

Here’s an example code snippet showcasing this functionality without using .replace:

function myTrim(x)     
{
  // Custom logic to remove leading and trailing white spaces
} 

function myFunction()
{
  var str = myTrim("    Hello World!   \t ");
}

Answer №1

Using the power of Regexp.exec, here is an example:

var re = /^\s*(\S[\S\s.]*\S)\s*$/gm;

function trim(str) {
  var result = re.exec(str);
  return (result !== null) ? (re.exec(str),result[1]) : '';
}

console.log('['+trim("Hello World!")+']')
console.log('['+trim("     Hello World!")+']')
console.log('['+trim("Hello World!  \t  ")+']')
console.log('['+trim("     Hello World!  \t  ")+']')

A key point to remember is that you need to re-execute re.exec if the initial result was non-null in order to clear the function's buffer.

Answer №2

If you're looking to steer clear of using built-in functions, the solution involves iterating through your string.

Here's a method that entails three iterations over the string:

  1. The first iteration is to eliminate any leading spaces
  2. The second iteration takes care of removing trailing spaces by going in reverse order
  3. Finally, the last iteration reverses the string generated from the previous step

function myTrim(str) {
  const isSpace = c => c === ' ' || c === '\n' || c === '\r' || c === '\t';
  const loop = (str, fn) => { for (const c of str) fn(c) };
  const loopReverse = (str, fn) => { for (let i = str.length - 1; i >= 0; --i) fn(str[i]) };
  
  let out = '';
  let found = false;
  loop(str, c => {
    if (!isSpace(c) || found) {
      found = true;
      out += c;
    }
  });
  
  found = false;
  let reversed = '';
  loopReverse(out, c => {
    if (!isSpace(c) || found) {
      found = true;
      reversed += c;
    }
  });
  
  out = '';
  loopReverse(reversed, c => out += c);
  return out;
} 

console.log(`[${myTrim('  \n  Hello World!   \t ')}]`);
console.log(`[${myTrim('Hello World! \n  \t ')}]`);
console.log(`[${myTrim('Hello World!')}]`);

Answer №3

Based on my understanding, you can give this a shot.

x.replaceAll("\\s", "");

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

How can one determine if an array in javascript contains anything other than null values?

I am dealing with an array that typically contains: [null, null, null, null, null] However, there are instances where the array may change to something like: ["helloworld", null, null, null, null] Instead of using a for loop, I am curious if it is po ...

Trying to assign a value to a property that is not defined

I'm attempting to initiate the loading and exhibition of a .stl file through three.js by implementing the following code: var stlLoader = new THREE.STLLoader(); stlLoader.load('assets/Cap.stl', function (object){ object.position.y = - 1 ...

Exclude objects in array that do not match filter criteria

I am facing a challenge with filtering an array of objects. (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {tbi_tblid: 512100013, long_name: "", short_name: "", short_name2: "", trickysort: "", …} 1: {tbi_tblid: 512100013, long_n ...

Issue with Jquery .ajax function returning an object even after it has already moved on to the next line of code

I'm currently working with JQUERY and AJAX, and it seems like the function is somewhat functional but there's a glitch that occurs after the next line of code runs. This issue causes the script to add a null value when trying to insert the object ...

JavaScript's functionality akin to PHP's exec() function

I am searching for a way to run a shell command through javascript, similar to the functionality of PHP's "exec()" function. I understand that executing shell commands in javascript may not be recommended due to security concerns. However, my javascri ...

"Can you tell me a way to identify variances between two dates displayed in a

I am looking to calculate the differences between two dates. I will input the date values in the text box and want the duration to be displayed in another text box. <script language=javascript> function formshowhide(id) { if (id == ...

What is the best way to resize images while also maintaining their ability to transition on hover?

Having an interesting dilemma here.. I'm trying to utilize this CSS code: .custom-forums { height: auto; width: 100%; border-image-source:transparent url("../images/forums.png") center top no-repeat; } in combination with: .custom-forum ...

Manipulating events through adjusting values of a JQuery-UI range-slider

My range-slider's values are being set with the code: $('...').slider( 'values', [ 0, 10000 ] );. However, I am facing an issue where this line triggers the change( event, ui ) event twice. Is there a way to ensure it only triggers ...

Can someone assist me in figuring out how to solve selecting multiple radio buttons at once

<script type="text/javascript"> let x = "1.html"; let y = "2.html"; function redirectPage(form){ for(let i=0; i<form.length; i++) { if(form.answerq[i].checked && form.answerw[i].checked && f ...

Firing ng-change with fileModel or input type="file"

Is there a way to trigger ng-change when a change occurs with this file directive? I have implemented a custom file directive for this purpose. The Directive: app.directive('ngFileModel', ['$parse', function($parse) { return { ...

Managing both clicking and hovering events on a single element, ensuring that the popup modal remains open as long as it is being hovered over

After successfully implementing click and hover functionality on an element, I was able to position the popup relative to the mouse pointer based on a previous solution. However, I am now facing an issue where I want the popup modal to be fixed in a specif ...

Utilize jQuery and HTML simplistically to display or conceal divs throughout a webpage

After developing some basic jQuery code using if-statements to toggle the visibility of Divs based on a select list in HTML, I am seeking ways to enhance this code: 1) How can I achieve the same functionality with fewer lines of code? 2) Rather than manu ...

Open a JavaScript file to retrieve data from a nearby JSON object

I've been trying to access a local JSON file using a JavaScript file, but for some reason it's not working. Even though I'm sure the URL is correct, the code keeps failing to retrieve data from the JSON object. JavaScript file: var pieData ...

Creating IPv6 Mask from IPv6 Prefix Using Javascript: A Step-by-Step Guide

Write a JavaScript/TypeScript function that can convert IPv6 prefixes (ranging from 0 to 128) into the corresponding mask format (using the ffff:ffff style). Here are some examples: 33 => 'ffff:ffff:8000:0000:0000:0000:0000:0000' 128 => ...

Converting to JSON can be done dynamically by adjusting the format based on the size of an array

Below is the flat array I have: let data = [ ["0000001", "PAUL", "Y", "PELUCHE", "DRAKE", "DOG"], ["0000002", "ECHEBEL", "Y", "CAT", ""], ...

The execution of the code may encounter errors initially, but it generally runs without any issues on subsequent attempts

I recently developed a piece of code to ascertain whether a value in the database is null or not. Here's the snippet: var table; var active = false; function CheckActive(table){ this.table = "table" + table + ""; var db = window.openDatabas ...

Experiencing Issues with File Downloading on Express Server with Axios and Js-File-Download Library

I developed a feature on my express server that allows users to download a file easily. app.post("/download", (req, res) => { let file_name = req.body.name; res.download(path.join(__dirname, `files/${file_name}.mp3`), (err) => { ...

Exploring the JSON Structure in NodeJS

My current json array is structured in the following way: [{"id": 1, "meeting": "1/3/2015 12:30:00 PM", "name": "John"}, {"id": 1, "meeting": "1/3/2015 13:30:00 PM"}, "name": "John"}, {"id": 2, "meeting": "1/5/2015 7:00:00 AM"}, "name": "Peter"}, {"id": 2 ...

The comparison between using multiple Vue.js instances and components, and implementing Ajax tabs

I am looking to incorporate ajax tabs using vue js. Each tab will need an ajax request to fetch both the template and data from an api. Here is an example of the tabs: <div id="tabs"> <ul class="nav nav-tabs"> <li class="active">& ...

Can you tell me if the "dom model" concept belongs to the realm of HTML or JavaScript?

Is the ability to use "document.X" in JavaScript to visit an HTML page and all its tags defined by the HTML protocol or the ECMAScript protocol? Or is it simply a choice made in the implementation of JavaScript, resulting in slight differences in every bro ...