How can I formulate a regular expression in TypeScript to extract the 'href' attribute value from a string?

Can anyone help me extract the 'href' (tag link location value) from the HTML text below using TypeScript?

String Text one

"<html><body><a href="C:\Users\K\Documents\docker_command.txt">docker_command.txt </a></body></html>"

String Text Two

"<html><body><a href="https://www.facebook.com/">https://www.facebook.com/ </a></body></html>"

Answer №1

Is this how you would approach it?

const x = '"<html><body><a href="C:\Users\K\Documents\python_script.txt">python_script.txt </a></body></html>"';
const y = '"<html><body><a href="https://www.twitter.com/">https://www.twitter.com/ </a></body></html>"';

function extractLink(html: string): string|null {
  if (!html) {
    return null;
  }

  return html.match(/ href=("|')([^'"]*?)('|")/i)[2];
}

console.log(extractLink(x));
console.log(extractLink(y));

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

How to delete the final character from a file stream using node.js and the fs module

My current project involves using node.js to create an array of objects and save them to a file, utilizing the fs library. Initially, I set up the write stream with var file = fs.createWriteStream('arrayOfObjects.json'); and wrote an opening brac ...

Exporting an enum without specifying a module flag

I have a piece of typescript code that defines an enum in file1.ts: // file1.ts export enum Status { Active = 1, NotActive = 0 } In another part of my project, I import the Status enum from file1: // file2.ts import {Status} from "./file1"; ... ...

Prevent TypeScript from allowing strings or arrays to be assigned to types with no properties

Can we limit the input for param so that it does not allow strings, arrays, etc.? interface bar { x?: number; y?: string; } function qux(param: bar) { } qux("hello"); ...

Increasing the Length of a String by 1-5 Characters

I am trying to manipulate a Java String to become a multiple of 5 by adding X's to the end: For example: "ABCDEFGHIJK" // length 11 Adding 4 "X" to the end should result in: "ABCDEFGHIJKXXXX" // length 15 Another example: "ABCDEFGHI" // length 9 ...

How can I toggle the visibility of a div after the DOM has finished loading?

I was experimenting with a radio button on the interface linked to a property in the typescript file that controls the visibility of another div. However, I noticed that both *ngIf="isFooSelected" and [hidden]="!isFooSelected" only function upon initial pa ...

Rotating Selection Item

I'm currently developing a pricing calculator that allows customers to choose from a spinner list and calculates the total price based on their selection. Although I have successfully created the spinner drop down list, each item in the spinner has a ...

Attempting to analyze a CSV document in which certain cells in the COLUMN are blank

I am attempting to parse data from a .csv file with 6 columns, but some rows have an empty cell in the last column. item1 2 4 125 200 item2 5 8 250 375 item3 2 3 125 200 item4 2 4 200 325 10 item5 1 2 325 400 10 item6 1 ...

What is the best way to display line breaks that are included within a string?

My strings with line breaks are currently rendering as <br> instead of actual line breaks. I attempted to use back-ticks but that did not work. Is there an easy way to display line breaks on the page without making significant changes to my code? H ...

The validation of DOM nesting has detected that a <td> element cannot be placed within an <a> element

When working on a React project with Material UI, I encountered an issue while trying to create a table. My goal was to make the entire row clickable, directing users to a page with additional information on the subject. Below is the snippet of code for th ...

What is the best way to create a function with the prototype 'void convertstring(char *)' for converting lowercase to uppercase in C?

Here is the code snippet I have crafted: #include <stdio.h> void modifyString(char *text[]) { int i; for (i = 0; *text[i] != '\0'; i++) { if (*text[i] >= 'a' && *text[i] <= 'z') ...

Is there a way to efficiently extract the "String response" from PHP using Retrofit on an Android device?

I am looking to input data from my android application into a database using retrofit. The following snippet shows part of the interface: @FormUrlEncoded @POST("*****") Call<model> insertChordReq(@FieldMap Map<String, String> fields); ...

Angular modal not responding to close event

My issue is that when I try to close a modal by pressing the X button, it doesn't work. Here is the button where I am triggering the modal: <button type="submit" id="submit-form" class="btn btn-primary" (click)="o ...

Managing different Vue dynamic components: mastering prop passing, event emitting, and slot replacement techniques

Just have some basic understanding of dynamic components, but what if the component is complex or unique from each other, how should I manage emit, props, and slots in the parent component? Let's say I have 3 components: Component 1 <template> ...

Custom type declaration file in Typescript fails to function properly

I have searched through countless solutions to a similar issue, but none seem to work for me. I am attempting to utilize an npm package that lacks TypeScript type definitions, so I decided to create my own .d.ts file. However, every time I try, I encounter ...

Tips for differentiating function that accepts various types of arrays with generics

I have come across a typings declaration that caught my attention: public static Loop<Type>(arr:Type[], callback:(obj:Type) => void):void; This declaration represents the structure of a function written in native JavaScript. It essentially itera ...

Verifying data types in TypeScript

When working with TypeScript in the browser, I often find myself writing code like this: const button = document.getElementById(id); if (!(button instanceof HTMLButtonElement)) { throw new Error("TODO -- insert better error message here"); } bu ...

Is there a simple method I can use to transition my current react.js project to typescript?

I am currently working on a project using react.js and am considering converting it to typescript. I attempted following an article on how to make this conversion but have run into numerous bugs and issues. Is there a simpler method for doing this conver ...

Simply output the integer value

Recently, I've been working on a function that I'm trying to condense into a one-liner code for a challenge on Codewars. You can find the problem here. Here's the code snippet that I currently have: export class G964 { public static dig ...

What steps should I follow to bring a telegram bot to life? Is it an issue if I try to integrate a module from Deno

import { TelegramBot, UpdateType } from "https://deno.land/x/telegram_chatbot/mod.ts"; <--- ISSUE import "https://deno.land/x/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a2a9b299a3a8b086f6e8f4e8f6"> ...

Transferring 'properties' to child components and selectively displaying them based on conditions

This is the code for my loginButton, which acts as a wrapper for the Button component in another file. 'use client'; import { useRouter } from 'next/navigation'; import { useTransition } from 'react'; interface LoginButtonPr ...