How to extract the text before a question mark using JavaScript regex if it exists

I'm dealing with a situation where I have strings like #test or #test?params=something

var regExp = /(^.*)?\?/; 
var matches = regExp.exec($(this).data('target'));
var target = matches[1];
console.log(target);

I always want to extract only #test. However, the current function throws an error if there is no question mark in the string. My objective is to consistently retrieve #test regardless of any additional parameters. How can I adjust the regex pattern to achieve this?

Answer №1

Does this string come directly from the URL of the current page?

If it does, you can easily extract it using:

window.location.hash.split('?')[0]

For example, if you're on http://example.com/#test?params=something, the code above will give you "#test".

Test Cases

example.com/#test                     -> "#test"
example.com/#test?params=something    -> "#test"
example.com/foo#test                  -> "#test"
example.com                           -> ""

Answer №3

Here's a straightforward option:

variable = stringValue.slice(0, (stringValue + "#").indexOf("#"));

Answer №4

Here is a helpful tip:

let pattern = /^([^?]+)/;

This regular expression will always extract the string before the first occurrence of ?, regardless of whether there is a ? in the input.

Check out RegEx Demo

Answer №5

It appears that either I am overlooking something or simply:

 ^#\w+

Is able to handle both of these situations (here and here) quite effectively

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

Automatic suggestions for my personalized npm module (written in ES6/Babel) in Webstorm

When I utilize the material-ui package in Webstorm, I am able to experience helpful auto-completion using the ctrl+space shortcut: https://i.stack.imgur.com/Pivuw.png I speculated that this feature may be attributed to the inclusion of an index.es.js fil ...

Working with NodeJS: Utilizing object casting with default values and eliminating superfluous

In the backend code of a NodeJS application, there is an object defined as follows: { name : "foo" secret : "bar" } The objective is to return this object as JSON in response to an HTTP request without including the secret key. The desired return obj ...

The Vue.js application is experiencing issues with displaying Google Maps functionalities

I have developed an application using Vue.js in Monaca and Cordova with onsenUI. My goal is to display my location on a Google map within the page. I attempted to achieve this by utilizing the npm package named vue2-google-maps, but unfortunately, it' ...

retrieve the position of a descendant element in relation to its ancestor element

I'm encountering a challenge while attempting to solve this issue. I have elements representing a child, parent, and grandparent. My goal is to determine the offset position of the child (positioned absolutely) in relation to the grandparent. However, ...

Ways to showcase an array within another array using VueJS

I encountered an issue with an API call that returns its result as an array within an array. Each nested array contains card transactions that need to be displayed. Upon examining the console output, I found: Array [ Object { "data": Array ...

Events triggered by client-side interactions with ASP.NET controls

Below is the image code I'm working with: <asp:Image runat="server" ID="imgLogo" Style="border-width: 0px; max-width: 100%; max-height: 200px;" onerror="showInvalidImageMessage();" onload="imageChanged()"/> Even though I want to trigger a Java ...

Learn the steps to merging all yarn files using gulp

After successfully setting up yarn and getting the hang of how it functions, I've also started to grasp the basics of gulp. I was relieved to find out how to install version 4 and avoid those deprecated errors that came with the default version. As o ...

How to eliminate a div using jQuery

Within a repeater, there is a button that should remove the respective div followed by a database query using AJAX when clicked. The issue arises when attempting to remove the div in the success part of the AJAX call. Here is the code snippet: <asp:Up ...

Refresh a different Angular Controller after submitting a POST request

Just to clarify, I am looking to dynamically reload another controller with new data after a POST request without refreshing the page. Here is my code: No issues with saving data to the database. Script var app = angular.module('userBase', []) ...

Utilizing Next.js named imports without server-side rendering

I am looking to update this code snippet to use next.js dynamic imports without server-side rendering (SSR) import { widget } from "./charting_library/charting_library"; Here is what I have tried so far const widget = dynamic(() => import(&qu ...

Exploring Node and Express Request Query

I'm struggling with a specific endpoint setup in my code. // GET /api/logs/ app.get('/api/logs', function (req, res) { if (req.query.reverse === true) { res.send((mainModule.logs).reverse()); } else { res.send(mainModule.logs) ...

The jQuery dropdown menu smoothly expands to reveal all hidden submenu options

I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 7 ...

Ensure all fields are valid prior to performing an update

I'm currently faced with the challenge of validating my form data before executing an AJAX update. Essentially, what I want to achieve is to validate the input data in the form before triggering the ajax update function. I'm unsure about where to ...

The redirection to a URL is not functioning correctly following an AJAX post

I am currently attempting to achieve the following: The goal is to pass a variable from ajax to Flask, which is posted in an input field. Once Flask receives this variable and inserts it into a MySQL table, I want to redirect the URL to a new page where t ...

AJAX using PHP returns an object containing null values

As a beginner in ajax programming, I encountered a small issue. I created a function in jQuery that makes an ajax call to a PHP file, which then retrieves information about a player from the database. However, when the PHP file responds to the ajax functio ...

Updating the ContextKey of the DynamicPopulateExtender based on the selected value from a DropDownList dynamically

I am facing an issue with my DynamicPopulateExtender control. I need it to render HTML based on the value of an asp:DropDownList. The problem lies in writing the JavaScript code that can fetch the dropdown value, assign it to the DynamicPopulate control&ap ...

Switching between 3 text options with the click of a button

I am in the process of creating a website and I want to be able to switch between displaying three different text values with the click of a button. Specifically, I am trying to toggle between USD and GBP values for standard and premium fees. Currently, I ...

Exploring the versatility of WebGL and Three.js with multiple materials on a single intricate grid structure

To enhance performance, I optimize by rendering the grid to a single THREE.Geometry() object using this loop: build: function(){ square = new THREE.Geometry(); face = 0; for(r = 0; r < this["rows"]; r++) for(c = 0; c < this["cols"]; c++) ...

Accessing information from database using Javascript

I am facing a dilemma with my HTML and PHP pages. The HTML page contains a table, while the PHP page executes a query to a MySQL table. I am struggling to display the query results on my HTML page. The HTML page features the following code snippet: <t ...

Is there a way to ensure one request completes before allowing another to be executed in Express/Node?

I am currently working on a task that involves fetching data from a third-party API (iTunes) to search for content provided by the API. The backend, which is handled by Express and Node, will interact with this third-party API. My goal is to trigger a POST ...