Regular Expression in JavaScript: Find all matches except those within [[ ]] brackets

My <textarea> contains a list of names with spaces between them, so I created a function to replace the spaces with new lines.

However, I now need to ensure that two or more spaces between names are considered part of the same element. For example:

John Lucas [[Laurie Vega]] [[Daniel Deer]] Robert

Should be transformed into:

John
Lucas
[[Laurie Vega]]
[[Daniel Deer]]
Robert

The regular expression

$("textarea").val().toString().replace(\ \g, '\n');
is not functioning correctly as it is adding new lines before "Vega" and "Deer."

I want to only replace spaces that are not between [ and ]. I tried negating the expression, but it's not working:

// Works
$("textarea").val().toString().match(/\[([^\]]*)\]/g));
// Am I using the ! operand wrong?
$("textarea").val().toString().match(/!\[([^\]]*)\]/g));

I'm feeling a bit confused. I attempted to match and replace, but then I realized I wouldn't be able to retrieve the original string. Therefore, I have to find anything outside of double brackets and replace the spaces.

Answer №1

If your names contain special characters like "-", "'", or spaces ("Jim-bo O'Leary"?), you may want to match anything that is not a '[' or a space using /[^[ ]/.

To achieve the new line effect, you can combine the matched strings together.

$("textarea").val().toString().match(/([^\[ ]+|\[\[[^\]]*\]\])/g).join("\n");

Answer №2

In a regular expression, the exclamation point doesn't hold any specific significance.

What you need to search for is either (indicated by the | symbol) a series of letters

[A-Za-z]+

or two square brackets, followed by some characters that are not closing brackets, and then two closing brackets

\[\[[^\]]+\]\]

Thus,

$("textarea").val().toString().match(/[A-Za-z]+|\[\[[^\]]+\]\]/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

What are some tips for efficiently troubleshooting a JQuery GET request to MailChimp 3.0 servers?

I am encountering an issue while trying to include users' emails in my Mailchimp 3.0 audience list. I am making a GET request using JQuery, but I keep running into the following error: {"type":"http://developer.mailchimp.com/documentation/mailchimp/g ...

Issue encountered when utilizing the childNodes.length attribute in JavaScript with elem

I am struggling to accurately find the count of child nodes in my treeview after implementing drag and drop functionality. Whenever I try to determine the number of child nodes, I keep getting a static value of 4 regardless of the actual number of children ...

Steps to include a fresh string into an array within a json document

I'm currently working on a Discord bot that uses a profile.json file. My goal is to have a specific command that allows users to add input arguments to an array within the file, like this: {"Profile_name":"id":"idhere", "array":["item_1"]} The ultim ...

Populate a dropdown menu in jQuery with options generated from an array

I'm planning to include 4 dropdowns in my project. My approach involves creating 3 arrays (the first dropdown is hardcoded). The idea is that based on the selection made in the first array, the options for the second dropdown will be populated. How ca ...

The data retrieved from the web API is not undergoing the necessary conversion process

I am facing an issue with a web API call where the property checkNumber is defined as a double on the API side, but I need it to be treated as a string in my TypeScript model. Despite having the property defined as a string in my model, it is being receive ...

Angular - transform expression result using specific values

I am attempting to modify the output of an expression based on a set of options stored in an object. Currently, I have an expression {{ resultItem.OdometerUnit }} that can result in one of three variations: hours kilometers miles My goal is to first ch ...

Inverting the order of vertices in a THREE.js face

I am seeking a way to reverse the order of vertices in faces within my geometry. For instance: // create geometry var geometry = new THREE.Geometry(); // create vertices geometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) ); geometry.vertices.push( ...

Chrome experiences a hidden stalling issue due to a large WebGL texture

While working with WebGL on Windows 10 using Three.js, I noticed that initializing a large (4096 x 4096) texture causes the main thread of Chrome to stall for a significant amount of time. Surprisingly, the profiler doesn't show any activity during th ...

Technique for adding an element's attribute to a span based on the element's class

I am aiming to display a maximum of three selections within my h4 tag, based on the number of options that the user clicks. For instance, the h4 tag should show 'Department1, Department 2,' if no elements are selected or have the class active, i ...

Executing ajax requests in MVC 5 using Webgrid

The objective: To dynamically update the webgrid without reloading the page using ajax when navigating to the next page. My current setup : public ActionResult Index() { var users = (from a in _context.Audit select new ...

Simple JavaScript Calculator

I'm currently working on a basic JavaScript Mortgage calculator, but I'm facing some challenges. I haven't implemented the math yet and I'm struggling to display the final sum (x + y + z) below the form after submission. The reset form ...

How to link an external CSS file to a Vue.js project

I created a new project using @vue/cli and now I want to add an external CSS file to my App.vue Here's what I attempted: <template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | ...

Show only the populated fields in a user profile with ReactJS

Purpose Showcasing only completed fields. Context In my app, users fill out an application with fields like "early reg fee, early reg date, regular reg fee, regular reg date". After completing all the information and clicking "view profile", they should ...

html displaying dynamic data in a table

As a beginner in coding, I am attempting to create a dynamic table. The first column is working fine with each new cell being added to the top. However, when I try to add columns, they fill from top to bottom instead of mirroring the first column. I want m ...

Fixing Laravel 5.2 and jQuery validation issue: Accessing a property from a Non-Object

Currently, I am utilizing the jQuery validation plugin to check whether a username already exists or not. The documentation regarding the validation plugin states: The server-side resource is accessed through jQuery.ajax (XMLHttpRequest) and receives k ...

Tips for preventing Chrome from masking the background image and color on an autofill input

Google Chrome Browser has caused the background-color and background-image effects to be removed from the Username and Password input fields. Before autocomplete https://i.stack.imgur.com/Ww7Hg.png After autocomplete https://i.stack.imgur.com/hbG2C.png ...

ReactJS & MobX: Unusual TypeError Occurs - Functionality Issue?

This code snippet defines the SidenavStore.js, which determines if the Sidenav should be visible or not by default: const SidenavStore = types .model('SidenavStore', { isSidenavVisible: types.optional(types.boolean, true), }) .actions( ...

Transform a dictionary into a SQLite database

I have a dictionary presented in the following format: Traditional Simplified [pin1 yin1] /English equivalent 1/equivalent 2/ ^1 ^2 ^3 ^4 ^5 For instance: 制 制 [A A zhi4] /to split the bill/to go Dutch/ ^1 ^ ...

Fiber react three selection group

I am attempting to combine/select multiple meshes as a group. Currently, my code looks like this: //wrapper <group onPointerOver={(e) => getOverEvent(e)} onPointerOut={(e) => getOutEvent(e)} onPointer ...

Unable to initiate the server in a new window due to the absence of a specified terminal application

When incorporating an external library into my React Native project, the installation process is usually smooth. However, when I try to integrate the library into my entire project and run 'react-native run-android' command, it shows an error. I ...