Reputation: 6976
I am creating a linking system that needs to be cross platform, i.e work on a webapp as well as a mobile 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?
Upvotes: 1
Views: 93
Reputation: 23816
Consider:
str = "Go to {P}Project Name{/P}"
str = str.replace(/({P}|{F})/, '<a href="">');
str = str.replace(/({\/P}|{\/F})/, '</a>');
alert(str);
Shorter updated solution:
str = "Go to {P}Project Name{/P}"
str = str.replace(/({P}|{F})(.*?)({\/P}|{\/F})/g, '<a href="">$2</a>');
alert(str);
Upvotes: 1
Reputation: 1199
You can use indexOf (pure JS) to check whether you can find {P} or {F} in your string. Then replace them.
var str = "Go to {P}Project Name{/P}"; //this is just an example, it may contains F
if (str.indexOf("{P}" != -1} {//will return -1 if it doesn't have
str = str.replace("{P}", "<a href="">");
str = str.replace("{/P}", "</a>");
} else {
str = str.replace("{F}", "<a href="">");
str = str.replace("{/F}", "</a>");
}
Upvotes: 0
Reputation: 175766
One way:
str = str.replace(/({[PF]}(.*?){\/[PF]})/g, '<a href="">$2</a>');
For Go to <a href="">Project Name</a>
Upvotes: 2
Reputation: 7230
I'd recommend looking at the JS regex tuturials either at Javascript Kit or at w3schools.
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]\}/
.
Upvotes: 0