skip to Main Content

I want to find a / symbol on given text and replace with * symbol.

http://localhost:7070/home/test/mobile:device.testdevice.id1_123.id2_456.id3_ab-c.CONSTANT_formula:map/TreeMap.json

Here the CONSTANT is fixed and it will not get changed but after CONSTANT there can be any character. I want find the CONSTANT in the url and look for / symbol and replace it with * symbol.

Something like this – http://localhost:7070/home/test/mobile:device.testdevice.id1_123.id2_456.id3_ab-c.CONSTANT_formula:map*TreeMap.json

I am trying with below regular expression but it matches everything after CONSTANT as I use one or more identifier

^CONSTANT(.+)

Is there any way find the / symbol and replace with * symbol?

2

Answers


  1. Using mod_rewrite rule you can do this to replace / with * after keyword CONSTANT:

    RewriteCond %{REQUEST_URI} ^(/.*CONSTANT[^/]*)/(.*) [NC]
    RewriteRule ^ %1*%2 [L,NE,R]
    

    Note that it will perform an external redirect after replacement in URL.

    We are using 2 capture groups in RewriteCond:

    1. ^(/.*CONSTANT[^/]*) matches everything upto CONSTANT followed by 0 or more of any char that is not /
    2. Then we match /
    3. (.*): Finally we match everything else in 2nd capture group
    Login or Signup to reply.
  2. By using JavaScript, just use String.prototype.replace.

    Let the regex seperates the string into two parts from CONSTANT. Replace all / to * in the latter one.

    const reg = /CONSTANT(.*)/g
    const s = "http://localhost:7070/home/test/mobile:device.testdevice.id1_123.id2_456.id3_ab-c.CONSTANT_formula:map/dir1/dir2/TreeMap.json"
    const fixedStr = s.replace(reg, (match, g1, idx, origStr) => {
        return origStr.slice(0, idx) + match.replace(///g, '*');
    });
    console.log(fixedStr)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search