wyc
wyc

Reputation: 55273

Regex to match single quotes within double quotes (separately)?

How to write a regex to match this (see arrows):

"this is a ->'<-test'" // note they are quotes surrounding a word

and other to match this?

"this is a 'test->'<-"

in JavaScript? (And then, say, replace them with double quotes?)

I want to match them separately with two regexs.

Upvotes: 0

Views: 97

Answers (3)

winner_joiner
winner_joiner

Reputation: 14695

Depence on the string, for the given string "this is a ->'<-test'"

"this is a ->'<-test'".replace(/'/g,"\""); // does both at the same time
// output "this is a ->"<-test""
"this is a ->'<-test'".replace(/'/,"\"").replace(/'/,"\"") // or in two steps
// output "this is a ->"<-test""
// tested with Chrome 38+ on Win7

the g in the first Version, does a global replace so it replaces all ' with \" (the Backslash is only the Escape Character). The second Version replaces only the first occurence.

I hope this helps

If you really, want match once the first and once the last(without selecting/replacing the first) you would have to do something like this:

"this is a ->'<-test'".replace(/'/,"\""); // the first stays the same
// output "this is a ->"<-test'"
"this is a ->'<-test'".replace(/(?!'.+)'/,"\""); // the last
// output "this is a ->'<-test""
// tested with Chrome 38+ on Win7

Upvotes: 1

aelor
aelor

Reputation: 11116

for the first case :

var str = '"this is a \'test\'"';
var res = str.replace(/'/, "#");
console.log(res);

=> "this is a #test'"

for the second case :

var str = '"this is a \'test\'"';
var res = str.replace(/(.*(?='))'/, "$1#");
console.log(res);

=> "this is a 'test#"

Also understand that the second case is taking into consideration only the last ' and the first case will only consider the first '.

update:

if you want to replace all the occurence of the first ' with something try this:

var str = '"this is a \'test\' there is another \'test\'"';
var res = str.replace(/'(\w)/g, "#$1");
console.log(res);

=> "this is a #test' there is another #test'"

for the second occurence try this:

var str = '"this is a \'test\' there is another \'test\'"';
var res = str.replace(/(\w)'/g, "$1#");
console.log(res);

=> "this is a 'test# there is another 'test#"

This ofcourse is a very manipulative approach and you may face exceptions cropping here and there. IMHO usage of regex and doing this in itself is an over complicated approach

Upvotes: 2

nu11p01n73R
nu11p01n73R

Reputation: 26667

First case

/'\b/

Regex Demo

"this is a 'test' there is another 'test'".replace(/'\b/g, '"'))
=> this is a "test' there is another "test'

Second case

/\b'/

Regex Demo

"this is a 'test' there is another 'test'".replace(/\b'/g, '"'))
=> this is a 'test" there is another 'test"

Upvotes: 3

Related Questions