Cleaning a string of word characters in Javascript: a step-by-step guide

I have been working on cleaning strings that were transformed from word text, but I am facing an issue with removing the special character '…'

When I click on the "clean" button, the script currently removes all dots and only one special character. However, I actually need to remove all occurrences of this special character.

Can someone help me identify where my mistake is in my code?

Here is the code snippet:


$scope.string = "My transformed string ………….........…...."

$scope.removeDots = function() {
    var em = document.getElementsByTagName('em');
    var reg = /\./g;
    var hellip = /…/g

    angular.forEach(em, function(item) {
        if (item.innerText.match(reg)) {
            item.innerText = process(item.innerText)
        }
        
        if (item.innerText.match(hellip)) {
            item.innerText = item.innerText.replace("…", "")
        }
    });
};

function process(str) {
    return str.replace(/^([^.]*\.)(.*)$/, function(a, b, c) {
        return b + c.replace(/\./g, '');
    });
}
Here is the Plunker link with the struggles.

Answer №1

This code snippet is addressing multiple issues that can be resolved by simplifying it to a single regex replace function called within the process function. This function will handle both periods and … entities.

 $scope.removeDots = function () {
        var em = document.getElementsByTagName('em');
        angular.forEach(em, function (item) {
              item.innerText = process(item.innerText)
        });
    };

    function process( str ) {
        return str.replace( /\.|…/g, '');
    }
});

Check out the Plunker demo for more details.

Answer №2

Every time the character . appears in the word process, you should replace it, but only make one replacement for the character ….

I believe a simple solution would be to use

.replace(/(\.|…)/g, '')
; by adding the g modifier, we ensure that every matching character is replaced.

Answer №3

To perform both substitutions, start by replacing all instances of … with a single dot (as it may be the only pattern present), and then changing any consecutive dots into one:

function modify( string ) {
    return string.replace(/…/g, '.').replace(/\.\.+/g, '.');
}

var example="My modified string ………….........…....";

console.log(modify(example));

The reason your previous code didn't work as expected is because you utilized a string as the search parameter, leading to just one replacement being made. By using a regular expression for the search query, you can achieve a global replacement effect akin to the g modifier.

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 come I am receiving a null value for isMatch from bcrypt compare even though the two password strings match exactly?

Currently, I am attempting to authenticate a user based on a password. My approach involves using bcrypt compare to check if the user's requested password matches one stored in a MongoDB database. Despite the passwords being identical, I keep receivin ...

The loading cursor in IE7 flickers incessantly, causing the webpage to lag and become un

When I move my cursor and click in text fields, the page becomes unresponsive and shows a wait cursor. If you're curious to see this issue in action, check out this video. This problem is specific to IE7. I've attempted to identify any ajax re ...

Convert a pandas dataframe into a JSON object with nested structures

Someone raised a similar question in a different forum, which was expertly answered by user1609452 using R. However, I believe there is more to explore with this topic. Let's consider a table (MyData) that looks like this: ID Location L_size L_co ...

Is it possible to independently verify the results of promises within a $.when(...) function without regard to the overall outcome?

Take a look at this example: $.when(a1, a2, a3, a4, .....) .done(function (){alert('done')}) .fail(function (){alert('fail')}); If all promises from a1 to ax were successful, I can manage and handle all the data within t ...

Using the foreach Loop in Javascript and AngularJs

Having trouble with a foreach loop because you're not sure of the column name to access specific data? Here's a solution to display all columns along with their corresponding data: angular.forEach(data, function(value, key) { console.log( &a ...

What is the best method for ensuring that cheese rises to the top?

Is there a way to increase the value of the variable cheese? I suspect it has something to do with how the variable cheese is defined each time the JavaScript is activated, but I'm not sure how to go about it. Can you offer some guidance on this? & ...

Issue: Assertion violation: The use of <Link> element is restricted to within a <Router>. Any solutions or suggestions?

In my React and Next Js application, I am utilizing react-router-dom for routing purposes. The dependencies listed in the package.json file are as follows: This is how my current package.json file looks: { "name": "MUSIC", "versio ...

An error being thrown within the error function of $http during a unit test is triggering a $digest already in progress

Have a look at this Plunker showcasing the issue: http://plnkr.co/edit/J8zRIj?p=preview If you check out this other Plunker where the error is no longer present in both scripts.js and scripts.spec.js, you'll see that the $digest error is resolved: ...

XPages component retrieval function is malfunctioning

Utilizing an XPage with JQuery dialog and client-side validation adds efficiency to the user input process. However, there seems to be a disconnect between the client-side validation and server-side properties. Although the client-side validation functions ...

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 ...

Utilize the power of dual API integration in a single request (multi-scope capability)

While there may not be a definitive answer to this question, I want to ensure that my situation cannot be resolved in any way. The crux of my application (and consequently the issue) is that each user possesses their own unique database and does not have ...

How do I retrieve and display all the locally stored variables in Angular 2/JavaScript and calculate the total number of keys present in the localStorage?

Currently, I'm developing a project in Angular2 that involves the storage of user-added items to a shopping cart. To accomplish this, I have opted to utilize local storage to temporarily save the items. Each category (such as shoes, clothes, etc.) is ...

Capturing Data from Tables and Saving it with Protractor

Imagine having a table structured like this <h2>HTML Table</h2> <table> <tr> <th>Company</th> <th>Contact</th> <th>Code</th> </tr> <tr> <td>Alfreds Fu ...

Ways to retrieve the initial value and proceed with a subsequent subscription method

I have created a basic angular 7 web application with Firebase database integration. In my code, I am attempting to store the initial list in an array using the subscribe method and then display that array using console.log(). However, there seems to be a ...

Tips for integrating execute_script and WebDriverWait in Selenium automation

Is there a way to combine execute_script() and WebdriverWait? In my current code: network_list = driver.find_element_by_xpath('//*[@id="folder_box"]/div[1]/div/div[2]/div[1]') wait = WebDriverWait(driver, 4) try: wait_network_list = wait.unt ...

How is it possible for my search results page to retrieve the words I input?

Currently, I am in the process of creating the search result page and I plan to utilize dynamic routing for implementation. Here is a snippet of my search bar code: <Link href={`/productSearchResult/${searchWord}`}> <a className={styles.navbar_s ...

Clicking React useState causes it to update before the intended click is registered

My goal is to create 50 buttons that, when clicked, will update the value of useState to the current button number (array index+1). However, I've encountered an issue where I have to click a button twice to get the correct value. The first click alway ...

Issue with vuejs build process not incorporating relative paths into the final output

I'm encountering a problem trying to run my Vue.js app from the dist folder. After searching on this site, I came across a helpful thread titled Vuejs, Difficulties to build with relative path, which suggested the following solution: Create a "vu ...

Creating responsive arrow heads using D3: A step-by-step guide

Currently, I am working on creating a thermometer-style bar chart using D3.js version 3. While I have successfully created a basic responsive rectangle with two filled colors, I am facing difficulties in figuring out how to add arrow heads to the design. B ...

Tips for transmitting `props` information between parent and child components using react router

Looking for guidance on how to properly pass props data from a parent component to a child component when navigating to a new route. I've attempted some solutions from this GitHub issue, but passing it through {...props} didn't work as expected. ...