Replace a character of a string

前端 未结 2 1487
萌比男神i
萌比男神i 2021-01-21 05:40

I have a string that looks like this: [TITLE|prefix=a].

From that string, the text |prefix=a is dynamic. So it could be anything or emp

相关标签:
2条回答
  • 2021-01-21 06:11

    You need to remember to use \\ in a regular string literal to define a single literal backslash.

    Then, you need a pattern like

    /(\[TITLE(?:\|[^\][]*)?)]/gi
    

    See the regex demo. Details:

    • (\[TITLE\|[^\][]*) - Capturing group 1:
      • \[TITLE - [TITLE text
      • (?:\|[^\][]*)? - an optional occurrence of a | char followed with 0 or more chars other than ] and [
    • ] - a ] char.

    Inside your JavaScript code, use the following to define the dynamic pattern:

    const regex = new RegExp(`(\\[${x}\\|[^\\][]*)]`, 'gi');
    

    See JS demo:

    let str = 'Lorem ipsum [TITLE|prefix=a] dolor [sit] amet [consectetur] [TITLE]';
    const x = 'TITLE';
    const regex = new RegExp(`(\\[${x}(?:\\|[^\\][]*)?)]`, 'gi');
    str = str.replace(regex, "$1|suffix=z]");
    console.log(str);
    // => Lorem ipsum [TITLE|prefix=a|suffix=z] dolor [sit] amet [consectetur]

    0 讨论(0)
  • 2021-01-21 06:26

    I think the solution to your problem would look similar to this:

    let str = 'Lorem ipsum [TITLE|prefix=a] dolor [sit] amet [consectetur]';
    
    str = str.replace(/(\[[^\|\]]+)(\|[^\]]*)?\]/g, "$1$2|suffix=z]");
    
    console.log(str);
    
    0 讨论(0)
提交回复
热议问题