Ask away

Javascript component replacing text in string with other text

Tony 10/10/17 17:41


Question CategoryComponent,Properties

Number of completed projects0

Question StatusUnsolved

  • javascript
  • component
  • text
  • string


I am creating a linking system that needs to be the nest component, i.e work on a hybrid app as well as a native app. The API returns a string that looks like this, Go to {P}Project Name{/P} OR Go to {F}File Name{/F} I need to search for an occurance of {P} and {F} and replace this with a <a href=""> on my webapp, and then search for {/P} or {/F} and replace that with </a> I am trying to do this with javascript but I am coming unstuck, here is what I have so far, var body = this.get('body'); if(body.match( \({P}|{F}/) { } after this I come unstuck my regex knowledge is not what it should be, can some point me in the correct direction?


John 10/21/17 22:28

str = "Go to {P}Project Name{/P}" str = str.replace(/({P}|{F})(.*?)({\/P}|{\/F})/g, '<a href="">$2</a>'); alert(str);

Lena 10/22/17 15:32

it seems to figure out that the { and } are literals, presumably because they don't have a number inside them. Still...

Donn 10/24/17 09:17

One way: str = str.replace(/({[PF]}(.*?){\/[PF]})/g, '<a href="">$2</a>'); For Go to <a href="">Project Name</a>

Karen 10/29/17 23:39

It fails when the string looks like Go to {P}Project Name{/P} as well as to {F}Project File{/F}

Chris 10/31/17 02:41

It would ouput Go to <a href="">Project Name</a>

David A 11/01/17 10:55

In your case, you're failing to open the regex with a slash (/), and there's also the fact that brackets ({}) have a special significance on a regular expression, so you'll have to escape it. Your regex should be something like /\{[PF]\}(.*?)\{\/[PF]\}/.

Cameron 11/09/17 00:23

Great advice added updated solution with escaping { & }. Thanks