skip to Main Content

I have the following string:

[url=https://www.youtube.com/watch?v=gk8ftgR9jK]Final digit was removed[/url]

I wish to replace the "]" char immediately following the YouTube v= string with a ">", but can’t quite get the regex correct.

I am only able to select the complete string up to the FINAL "]", which is not what is required.

atag.replace(/https://.*?]/, etc) //Haven't worked out the grouping yet, so "etc"

3

Answers


  1. You could match and replace on the first [...]:

    var url = "[url=https://www.youtube.com/watch?v=gk8ftgR9jK]Final digit was removed[/url]";
    var output = url.replace(/^[(.*?)]/, "[$1>");
    console.log(output);

    Or another slightly different version:

    var url = "[url=https://www.youtube.com/watch?v=gk8ftgR9jK]Final digit was removed[/url]";
    var output = url.replace(/(.*?)]/, "$1>");
    console.log(output);
    Login or Signup to reply.
  2. You could capture the part right before matching the ] in group 1 and then match ] after it. In the replacement use group 1 to keep that part and add the character > after it.

    (https://[^][]*)]
    

    Regex demo

    For example:

    const atag = "[url=https://www.youtube.com/watch?v=gk8ftgR9jK]Final digit was removed[/url]";
    const result = atag.replace(/(https://[^][]*)]/, "$1>");
    console.log(result);

    Or a bit more specific and keeping the closing ] for the tag:

    [url=https://[^][]*]
    

    Regex demo

    const atag = "[url=https://www.youtube.com/watch?v=gk8ftgR9jK]Final digit was removed[/url]";
    const result = atag.replace(/[url=https://[^][]*]/, "$&>");
    console.log(result);
    Login or Signup to reply.
  3. You can also use ^([url=https?://(?:www.)?youtube[^rn]]+v=[a-z0-9]{10})]([^rn[]+[/url])$ and replace it with $1>$2:

    const regex =
      /^([url=https?://(?:www.)?youtube[^rn]]+v=[a-z0-9]{10})]([^rn[]+[/url])$/gi;
    
    const str =
      "[url=https://www.youtube.com/watch?v=gk8ftgR9jK]Final digit was removed[/url]";
    console.log(str.replace(regex, `$1>$2`));

    Note:

    This pattern has many restrictions that you might wanna use:

    • ^ is a start anchor.
    • ([url=https?://(?:www.)?youtube[^rn]]+v=[a-z0-9]{10}) is the capture group $1.
      • [url=https?:// validates http or https.
      • (?:www.)? optionally allows www..
      • youtube only allows youtube.
      • v=[a-z0-9]{10} checks for v followed by 10 alphanumeric chars.

    ]: ignores the bracket you want to replace.

    • ([^rn[]+[/url]) is the second capture group.
    • $ is an end anchor.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search