Make sure to leave a space after a period in a sentence, but do

My question is about fixing spacing issues in text, specifically sentences that lack spaces after a dot. For example:

See also vadding.Constructions on this term abound.

I also have URLs within the text, such as:

See also vadding.Constructions on this term abound. http://example.com/foo/bar

Answer №1

Locate and extract a URL while also identifying all other occurrences of dots and converting them to a dot followed by a space:

var re = /((?:https?|ftps?):\/\/\S+)|\.(?!\s)/g; 
var str = 'See also vadding.Constructions on this term abound.\nSee also vadding.Constructions on this term abound. http://example.com/foo/bar';
var result = str.replace(re, function(m, g1) {
return g1 ? g1 : ". ";
});
document.body.innerHTML = "<pre>" + result + "</pre>";

The regular expression for the URL - (?:https?|ftps?):\/\/\S+ - identifies patterns starting with http, https, ftp, or ftps, followed by :// and one or more non-whitespace characters (\S+). For more complex URL matching expressions, resources like Stack Overflow can provide useful insights. Check out What is a good regular expression to match a URL?.

Explanation of the process in more depth:

The regex

((?:https?|ftps?):\/\/\S+)|\.(?!\s)
presents two options: either identifying a URL (as explained above), or (|) recognizing a dot that is not followed by whitespace (\.(?!\s)).

IMPORTANT: The use of (?!\s) serves as a negative lookahead assertion to locate a dot not succeeded by a space.

When utilizing string.replace(), it's possible to specify an anonymous callback function as the second argument to handle matches and captured groups. In this case, there's one match value (m) and one capture group value g1 (representing the identified URL). If the URL is found, g1 won't be null. Therefore, return g1 ? g1 : ". "; preserves group 1 if matched, replacing standalone dots with . otherwise.

Answer №2

If you want to target the period character that is not followed by two or three lowercase letters or a space, consider using RegExp

/(\.)(?!=[a-z]{2}\/|[a-z]{3}\/|\s+|$)/g

"To learn more about this subject, check out myriad resources available online at http://example.com/foo/bar"
.replace(/(\.)(?!=[a-z]{2}\/|[a-z]{3}\/|\s+|$)/g, "$1 ")

Answer №3

Using inspiration from @MarcelKohls

var phrase = "Explore more: Resources about this topic are widely available. http://sample.com/foo/bar";
var url_pattern = /(\bhttps?:\/\/(?:(?:(?!&[^;]+;)|(?=&amp;))[^\s"'<>\]\[)])+\b)/gi;
phrase = phrase.split(url_pattern).map(function(phrase) {
  if (phrase.match(url_pattern)) {
    return phrase;
  } else {
    return phrase.replace(/\.([^ ])/g, '. $1');
  }
}).join('');
document.body.innerHTML = '<pre>' + phrase + '</pre>';

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

Having trouble getting Vue.js hello world to display on the page

I am attempting to create a Hello World app following the Vue.js site's get started documentation. Everything seems to be in order, but only the HTML code is being displayed on the page. Vue version: 1.0.26 Below is the HTML code: <!DOCTYPE ht ...

I am encountering an issue with CreateJS where I receive the error message: "createjs is not defined"

Looking for assistance with my createJS issue. var stage = new createjs.Stage(canvas); Encountering the following error : angular.js:13642 ReferenceError: createjs is not defined, even though I have EaselJS in my bower-components. Appreciate any hel ...

D3.js Issue: The <g> element's transform attribute is expecting a number, but instead received "translate(NaN,NaN)"

I encountered an error message in my console while attempting to create a data visualization using d3. The specific error is as follows: Error: <g> attribute transform: Expected number, "translate(NaN,NaN)". To build this visualization, I ...

While the Mongoose aggregate query is functioning properly in MongoDB, I am encountering difficulties in converting it to a Mongoose

Here is the JSON structure provided: [{ "_id" : ObjectId("626204345ae3d8ec53ef41ee"), "categoryName" : "Test Cate", "__v" : 0, "createdAt" : ISODate("2022-04-22T01:26:11.627Z"), "items" : [ { ...

What is the best method for extracting only file names from a SQLite dump?

My goal is to extract all file names from an SQLite text dump using Ruby. I don't have much experience with regex and I need a solution for extracting image file dumps from the SQLite dump so that I can read and write to another file. The challenge li ...

Verifying file types with HTML5 drag and drop feature

Is it possible to change the drop zone's background color to green or red based on whether the dragged payload contains supported file types (JPEG)? Do Gecko and Webkit browsers have the ability to determine the file type of drag and drop files? ...

Minimize a pop-up window and navigate to a different webpage

I have created a login/logout form that includes the option to delete my account. When I click the "Sterge cont" button, a pop-up window appears asking if I truly want to delete the account. If I select "NU," the account will not be deleted and the window ...

You've got a function floating around without any specific theme tied to it. Make sure one of the parent elements is utilizing a ThemeProvider for proper context

I am working on implementing a Navbar in my current Project. The dependencies I am using are: mui/icons-material: ^5.2.5 mui/material: ^5.2.6 mui/styles: ^5.2.3 Here is the folder structure of my project: Root.jsx Navbar.jsx styles ...

Content in static JSON file failing to display in NextJS

I recently started using Next, and I've encountered an issue. There is a static JSON file located in the root of my project directory, structured as follows: {"data":[{"id":1,"attributes":{"name":"Test Prod ...

Transform the text area in preparation for a GET request

Trying to figure out how to pass the text from a textarea into the source attribute of an image tag while retaining all formatting, including line breaks. After some research, it seems that the best way to accomplish this is by base 64 encoding the text a ...

Experience the convenience of Visual Studio Code's auto-completion feature for HTML tags even when working within an

My HTML file has a babel script embedded within it. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React tutorial</title> <script src="https://unpkg.com/react@16/umd/react.development.js" ...

purging data from javascript objects

In my Node.js HTTP server, I am using 'connect' to build a web service that currently parses JSON requests into an Object, performs operations, and returns a synchronous response. The JSON data comes from an ecommerce cart and results in an Objec ...

Using asynchronous import statements in Vue allows for more efficient loading of components

I am using Vue and have a method in my file called load.js. async function loadTask(x) { return await x; // Some async code } export { loadTask }; In one of my Vue components, I call the method but encounter an issue where the use of await prevents the ...

Obtain the dynamic $scope variable within the HTML structure

When creating numerous directives with dynamic scope variables initialized in the link functions, accessing these values within the directive templates can get tricky. For example: // link: function(scope, ele, attr){ scope.key = scope.somevar + 's ...

What about nested elements with percentages, set positions, and fixed placements?

Picture: I am working on a design with a yellow container div that I want to keep at 50% width of the window. Inside this container is a purple image div that stretches to 100% of the parent container's width, and there is a pink sticky label positi ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

Utilizing nested HTML within an HTML tag

Recently, I've been exploring the concept of nested HTML in Bootstrap. While following a tutorial on using Popovers, I encountered the following code; <button id="btn3" type="button" class="btn btn-primary show" ...

I am looking to narrow down the Google Places autocomplete suggestions specifically for India within Next Js

In my current project developed with Next.js, I am utilizing the react-places-autocomplete package to enhance user experience. One specific requirement I have is to filter out location suggestions for India only, excluding all other countries. Despite att ...

Discover the following item using jQuery

Here is some HTML code that I have: <div class="form-group"> <input type="text" class="sequence valid"> </div> <div class="form-group"> <input type="text" class="sequence valid"> </div> <div class="som ...

In CodeIgniter, the $this->input->post() function consistently returns an empty value

I'm encountering an issue where the value from an AJAX post always turns out empty. Even after confirming that the value is correct before the post, I'm unable to retrieve it using $this->input->post() HTML <?php if ($product_info-> ...