2

Here's my problem. I want to replace all the "document 1", "document 12" strings in a text by an hypertext link :

<a onclick="gotodocument(document7);">document 7</a>

I tried this code :

var reg=new RegExp("((document )[a-zA-Z0-9/.]+)+\s(\w+)","gi");
var chaine= *thetext*;
  var socle_contenu = chaine.replace(reg, "<a onclick=\"alleraudocument('$1');\"'>" + '$1' + "</a>");

The result is :

 <a onclick="gotodocument(document 7);">document 7</a>

As you can see, the problem is the space in the onclick function.

I tried to delete this space but I want to keep this space for the human reader. I couldn't make it.

I then tried to get "document " and the number in $1 and $2, in order to contacatenate the two variables as I need. I tried this :

var reg=new RegExp("((document )\s(\w+))+", "gi");

But it doesn't work ! Can anyone tell me how to setup the regular expression ?

Thanks !

2 Answers 2

1

You could use a callback function with the replace. This allows further manipulation of the matches:

var s = 'document 12 some more text document 7 end';

var re = new RegExp(/(document\s?\d+)/gi);

s = s.replace(re, function($1){ 
    return "<a onclick=\"alleraudocument('" + $1.replace(' ', '') + "');\">" + $1 + "</a>";
});

see demo here

Sign up to request clarification or add additional context in comments.

Comments

1

If the part about document is static, you can ignore that and only match the number you need. Then create the appropriate Link:

document\s*(\d+) with the replacement <a onclick="gotodocument(document$1);">document $1</a>

https://regex101.com/r/tB5lD8/2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.