wyc
wyc

Reputation: 55263

JavaScript: Replacing characters on both sides of a string

What I want to do is to match characters enclosed by ^^ and replace those ^^ while maintaining the string. In other words, turning this:

^^This is a test^^ this is ^^another test^^

into this:

<sc>This is a test</sc> this is <sc>another test</sc>

I got the regex to match them:

\^{2}[^^]+\^{2}

But I'm stuck there. I'm not sure what to do with the other .replace parameter:

.replace(/\^{2}[^^]+\^{2}/g, WHAT_TO_ADD_HERE?)

Any ideas?

Upvotes: 0

Views: 329

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

Here is a piece of code you can use:

var re = /(\^{2})([^^]+)(\^{2})/g; 
var str = '^^This is a test^^ this is ^^another test^^\n\n<sc>This is a test</sc> this is <sc>another test</sc>';
var subst = '<sc>$2</sc>'; 

var result = str.replace(re, subst);

This is just an enhancement of your regex pattern where I added capturing groups. To improve performance and ensure you will be capturing all symbols between the ^^, you can use only one capturing group and . symbol with non-greedy quantificator:

var re = /\^{2}(.+?)\^{2}/g; 

Have a look at the example.

Upvotes: 2

mohamedrias
mohamedrias

Reputation: 18566

In this case you need to use the group index to wrap the content.

var content  = "^^This is a test^^ this is ^^another test^^";

content.replace(/\^{2}(.*?)\^{2}/g, '<sc>$1</sc>');

The (.*?) will help you to group the content and in your replace statement use $1 where 1 is the index of group.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can use replace with regex and grouping like

var text = '^^This is a test^^ this is ^^another test^^'.replace(/\^\^(.*?)\^\^/g, '<sc>$1</sc>')

Upvotes: 5

Related Questions