Mr.Chowdary
Mr.Chowdary

Reputation: 3417

Replace special chars in between only, not start and end of the string?

I need to replace special character '(apostrope) with \'(back slash apostrope) but this should be only in between the string except starting and ending characters of the string.
eg: msg ='My Son's Daughter';
There can be multiple apostropes in the string. I just want to replace apostropes in the string which are not starting and ending characters.

Please share me any ideas.

Upvotes: 4

Views: 1827

Answers (3)

nl-x
nl-x

Reputation: 11832

Try

msg = msg.replace(/(.)'(.)/g, "$1\\'$2");

The . at beginning and end will require any character before and after the '.

The () will catch that charachter defined in it (.) to a variable ($1 and $2).

The $1 and $2 represent the catched character of both ().

The \\ escapes/represents a literal \

The / at the start, just before the g defines this as a Regular Expression (regex)

The g is a modifier (global) that will indicate ALL occurrences.

The regex should NOT be put between quotes as if it was a string.

Upvotes: 2

MrCode
MrCode

Reputation: 64536

Using a combination of substr() and regex:

var msg ="'My Son's Daughter'";

msg = msg.substr(0, 1) + msg.substr(1, msg.length-2).replace(/'/g, "\\'") + msg.substr(msg.length-1, 1);

Outputs:

'My Son\'s Daughter' 

As shown, only the inner ' are replaced, the first and last are ignored.

Upvotes: 4

alnorth29
alnorth29

Reputation: 3602

The replace function is what you're after. This should do the trick:

msg = msg.replace(/'/g, "\\'");

Upvotes: 0

Related Questions