The regex pattern checks for the presence of '<' followed by a space or

When using a multi-line textbox, I encountered the following string:

index a<3

2<x

I want to use regex to add a space after the character '<' if there isn't already one present. If there is already a space after the character '<', it should remain untouched.

The desired output should be:

index a< 3

2< x

I attempted to use (?<=<)(?!$) and <[^\s]+, but they resulted in syntax errors when used within Javascript.

While these solutions work on the back end (C#), I would prefer not to make a server request for this task as it is not an ideal solution.

Answer №1

Check out this unique technique without relying heavily on regex (alright, just a small amount of regex in the split)

document.querySelector( "textarea" ).addEventListener( "blur", function(){
  var value = this.value;
  //console.log( value );
  this.value = value.split( /\n|\r/ ).map( function(item){
    //console.log( item, item.split( /<|<\s/ ) );
    return item.split( /<\s|</ ).join( "< " );
  }).join( "\n" );
})
Click outside of the textarea below to witness the added spacing
<textarea>
index a<3 
index a<3 
</textarea>

Answer №2

To implement a basic regex, try using: <\b and substitute it with < ('<' plus space).

Answer №3

To match any non-space character in JavaScript, you can utilize the \S pattern which is equivalent to a negated character class, [^\s]. Due to the lack of look-behind support in Javascript, one way to achieve this is by matching the < symbol followed by a non-space character and then replacing it with the same < symbol along with a space.

str = str.replace(/<(?=\S)/g, '< ');

// or using negative lookahead
str = str.replace(/<(?!\s)/g, '< ');

var str = 'index a<3\n2<x';


console.log(
  str.replace(/<(?=\S)/g, '< '),
  '\n\n',
  str.replace(/<(?!\s)/g, '< ')
)

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

Splitting a loading button within post.map() in React for like/dislike functionality

I'm currently working on implementing a like/dislike feature in React. The issue I've run into is that when I try to like or dislike a post, the like/dislike buttons on all other posts are stuck in a loading state. This means that while I'm ...

Vue.js - the value of this is not defined

<div class="content-chart"> <chart :type="'line'" :data="lineData" :options="options"></chart> </div> In the template section above, a component is defined to render a chart using Chart.js. The script below handles the l ...

The message that keeps popping up says "TypeError: Unable to access the 'execute' property of an undefined object."

I am currently working on creating a Discord bot and encountering an error that says "TypeError: Cannot read property 'execute' undefined". Despite trying multiple solutions, I am still facing some issues with my code. Any help in solving this pr ...

The process of using Jest to test whether a React component correctly renders a list

I've been diving into the world of unit testing and recently developed a small React application that showcases a list of Pokemon. My goal is to create a unit test that verifies if the list renders correctly. However, when I generate a snapshot, it on ...

problem arising from the origin preventing me from utilizing localStorage in conjunction with JSDOM

Currently, I am facing an issue while trying to load a webpage in a node environment using JSDOM. The webpage relies on localStorage for its functionality. I have attempted to load the webpage by utilizing JSDOM's URL configuration option and accessi ...

React's nested map function is failing to display any results

My objective is to loop through nested arrays in the response data, which is an array containing other arrays. However, I am encountering an issue where the data is not being displayed for some reason. Here is an example of one item in the response: id: 5 ...

Best practices for defining module-wide constants in AngularJS

In my project, I have around 20 "modules" each with its own unique functionality but following the same structure. These modules are stored in separate files within their respective folders. For instance, the admin module is located in the modules/admin fo ...

Tips for transforming the input date value from Mui Datepicker

import * as React from "react"; import moment from "moment"; import TextField from "@mui/material/TextField"; import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; import { LocalizationProvider } from &quo ...

Is there a way to detect when a Bootstrap Alert is displayed?

I am using a flask app that flashes messages to an HTML file. When these flashed messages are caught, they are displayed as a bootstrap alert. Here is an example: {% with messages = get_flashed_messages() %} {% if messages %} {% for message in mes ...

Template7 produces a bizarre outcome referred to as "each this" whenever JSON is utilized

Currently, I am experimenting with dynamically loading content on Framework7/Template7 pages. Everything works perfectly fine when using static "context" in JSON format. However, when attempting to test it with real-world data from an API, I encounter a st ...

Different approach to handling response interceptors in AngularJS framework

Is there an alternative to $httpProvider.responseInterceptors since it has been discontinued in AngularJS V1.3? The interceptors that were functioning with Angular JS 1.2 are no longer operational in version 1.3 var angularErrorHandling = angular.module( ...

Sort out the information in the table

Seeking assistance on how to filter a table based on certain conditions. Refer to the sample image provided in the link below: https://i.sstatic.net/Egvj6.png Here is the code I have attempted: this.reportData.filter(it => { if ( ...

Retrieving blog posts formatted in markdown from a centralized JSON file

My current setup involves using react-markdown to load markdown content from a JSON file. I have opted for a static site hosted on CloudFront to save money and eliminate server operation costs. All posts are compiled into a posts.json file which is then ...

Monitoring changes to localstorage in AngularJS

How can I monitor changes to localStorage using $watch? I have created a factory to simplify setting and getting values .factory('$localstorage', ['$window', function($window) { return { set: function(key, value) { ...

The issue of variable stagnation in Firefox content script while utilizing self.port.on

I'm having trouble updating the version var as intended. When I try to update it with the following code: self.port.on("get-version", ver => { version = ver; alert(version); }); An alert pops up displaying the correct version number, but the HTML ...

Choose the DIV element based on its data attribute using JSON

When using each(), my goal is to: Hide all divs where the data-infos.grpid = $jQuery(this).data('infos').grpid Show the next div where data-infos.ordre = $jQuery(this).data('infos').next_ordre I am unsure how to apply a "where" ...

What is the best way to capture a screenshot using Gherkin-Cucumber with Testace as the preferred framework?

While attempting to capture a screenshot following a failed step: const { After } = require('cucumber'); After(function (scenario) { if (scenario.result.status ==='failed') { var world = this; return browser.takeSc ...

Customizing React component properties within a Styled Component

I have been experimenting with styled components to customize the appearance of basic material-ui React components. My goal is to pass props into the MUI component and then use styled components to apply CSS styling. One interesting aspect is being able t ...

I'm curious about how I can selectively utilize vuex-persistedstate with Nuxt for certain stores only

Check out this library: https://github.com/robinvdvleuten/vuex-persistedstate. I have customized the provided plugin file for Nuxt. import createPersistedState from 'vuex-persistedstate' export default ({ store }) => { createPersistedState ...

What steps can be taken to fix the error message 'Uncaught TypeError: (...) is not a function'?

I have already checked a similar question on stackoverflow, but it does not address the specific issue I am facing with the error. My goal is to ensure that both scripts, embed.js (plugin) and more-content-arrow.js (custom script), work correctly on the p ...