Search code examples
javascriptlodash

javascript replace all next text


I have this text for example

'test test: field test test 1 - pid 20242004 test test test 543 - pid 20242004 test test test 123 - pid 544745456 test test jdfh 1 - pid 353545 test test test 1 - pid 20242004 test test test 6 - pid 878 field test test 23 - pid 234445'

and I want to change all the text next the word 'pid' so the output will be:

'test test: field test test 1 - pid <a>20242004</a> test test test 543 - pid <a>20242004</a> test test test 123 - pid <a>544745456</a> test test jdfh 1 - pid <a>353545</a> test test test 1 - pid <a>20242004</a> test test test 6 - pid <a>878</a> field test test 23 - pid <a>234445</a>'

is there any way to do that with javascript?


Solution

  • You could do that with regular expressions

    in this expression i try to fetch any string that has the word pid and after it it has chunk of digits

    let str = 'test test: field test test 1 - pid 20242004 test test test 543 - pid 20242004 test test test 123 - pid 544745456 test test jdfh 1 - pid 353545 test test test 1 - pid 20242004 test test test 6 - pid 878 field test test 23 - pid 234445'
    
    let newStr = str.replace(/pid ([\d]+)/g, `pid <a>$1</a>`)
    
    console.log(newStr)

    for more info about replace check MDN