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

Is it more efficient to use Vue events or Vuex for transmitting data between components?

Working on a project where data needs to be shared between components in order to update a canvas element at 30-60fps for optimal performance on low-end devices. Currently utilizing Vuex store/get method for data transfer, but considering using events as ...

Dynamic styling updates on page refresh in Next.js

There is a strange issue with my styling that I can't seem to figure out. I have a NavBar set to be 20vh in height and an image set to be 100% in width. However, whenever I refresh the page, the NavBar height decreases and the image width increases si ...

What is preventing this Javascript from running in Firefox and Chrome?

I recently encountered an issue with some Javascript code that functions correctly in Internet Explorer, but fails to work on Mozilla Firefox or Google Chrome. Any insights as to why this might be the case? function returnData(strCode,strProgramCode,strNa ...

What is the best way to incorporate keyboard shortcuts into carousel operations using jQuery?

The example can be found here. I want to be able to navigate through the images using the left and right arrows on my keyboard. How can I achieve this using jQuery or CSS? This is the structure of the HTML: <div id="slider-code"> <a cla ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

The child component is not updating the v-model prop array of the parent component

In my current project, I have a main component called cms-custom-editor: <template> <div id="cms-custom-editor" class="cms-custom-editor"> <cms-editor-toolbar v-model:toggles="state.toggles"/> <d ...

What are your thoughts on the practice of utilizing the useState hook within a component to send data to its parent component?

I have been working on developing an Input component that can be dynamically used in any page to store input values. The component also includes an attribute called getValue, which allows the parent component to access the input value. In my App.js file, I ...

LESS: Using variable values in mixin and variable names

I am looking to simplify the process of generating icons from svg-files while also creating a png-sprite fallback for IE8 support. I am using grunt.js and less. I was inspired by the implementation on 2gis.ru: (in Russian), where they used technologies s ...

Cleaning up React async functions using hooks for fetching data

This code snippet is from a functional component. Within this component, there is a submit() function that handles form submission: async function handleSubmit(event) { event.preventDefault(); try { let resp = await fetch("FOOBAR/BAX", { ...

Bring in SASS variables to enhance Material UI theme in NextJS

Within my project, I currently have the following two files: materialTheme.ts import { createMuiTheme, Theme } from "@material-ui/core/styles"; const theme: Theme = createMuiTheme({ palette: { primary: { main: "#209dd2", contras ...

What are the steps to kick off my React App once I've cloned it?

Currently grappling with deploying my app using Netlify, I encountered an issue after cloning the app onto my new computer. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afee5eee5e6e3f9fefcb8cabba4baa4ba">[email  ...

Recharge Backbone prior to a lockdown

I'm currently utilizing a script within Backbone in a Cordova application (Android) that causes the app to freeze for 5 seconds, and unfortunately I am unable to find an alternative method. Due to this issue, I would like to display a loading message ...

There seems to be an issue with byRole as it is failing to return

Currently in the process of migrating my unit test cases from Jest and Enzyme to React Testing Library. I am working with Material UI's Select component and need to trigger the mouseDown event on the corresponding div to open the dropdown. In my previ ...

Improving Page Load Speed with HTML Caching: Strategies for Enhancing Performance when over half of the data transferred is for navigation menus

I manage a complex and expansive website that contains a significant amount of repetitive HTML elements such as the navigation menu and top ribbon. Loading a single page on my site can be resource-intensive, with up to 300KB of data required, half of whic ...

Excerpts capturing the significance of HTML attribute values

$(document).ready(function () { for (var n = 0; n < 3 ; n++) { $("body").append("<p id=\"element"+n+"\">Greetings, I am Element " + n + ".<p>"); } }); In the third line of code, which pairs of quotation marks match ...

Node Selenium for Importing Excel Files---I will help you

My current challenge involves using node selenium in Firefox to click a link that triggers the download of an excel file. I want the downloaded file to be saved in a specific directory, but when I click the link, a dialog box pops up giving me the option ...

In JavaScript, navigate to a new page only after successfully transmitting data to the server

Creating a redirect page that sends data to the server before transitioning to a new page can be achieved using JavaScript as shown below. <body> <script type="text/javascript"> **** Discussion of cookie-related transactions **** document.c ...

Fixing the Material UI upgrade error: "Make sure you have the right loader for this file type."

As a beginner in React, Webpack, Babel, and web development, I have been tasked by my company to upgrade the material-ui version for a dropdown search component. The current version used in the project is "1.0.0-beta.43", and I decided to start by upgradin ...

Creating a HTML and JavaScript carousel without relying on the animate function

I am currently facing some challenges with building a custom slider. While it moves forward smoothly using CSS animation, I'm struggling to implement a backward motion with an animation. It seems like I need to loop through the slides and try a differ ...

How can I store an access token received from the backend (in JSON format) in local storage and use it to log in?

My goal is to create a login interface using Plain Javascript. I have obtained a Token from the backend and now need assistance in utilizing this Token for the login process and storing it in LocalStorage. Although I have successfully made the API call, I ...