crankshaft
crankshaft

Reputation: 2677

javascript regex to capture single quotes when not surrounding text

I am trying to capture double-single quotes when they do not encapsulate other text.

What I am aiming for is 'hello ''world''

I have tried using the ! not on the text but that won't work, how can I capture this ?

var str = "hello '' ''world''"

// > hello '' ''world'' 
console.log(str.replace( /''![a-z]{1,}''/g),'');

// > hello  world
console.log(str.replace( /''/g,''));

// desired output > hello ''world''

EDIT

Sorrie, I was trying to create a simple example and have some answers that work for the original example, but I need to replace the '' with NULL instead of nothing i.e.

// desired output > hello NULL ''world''

Upvotes: 0

Views: 55

Answers (2)

acdcjunior
acdcjunior

Reputation: 135762

Character negation inside character classes (a.k.a. Negated character classes) are achieved using the ^ char.

So, in your case, replace the ! with ^. Try this:

var str = "hello '' ''world''"

// > hello NULL ''world'' 
console.log(str.replace( /''([^a-z]{1,}'')/g,"NULL$1"));

For a more complete example, maybe this would be better suited:

var str = "hello '' ''world'' ''hello'' '' world"

console.log(str.replace( /(^|[^a-z])''([^a-z]+|$)/g,"$1NULL$2"));
// > "hello NULL ''world'' ''hello'' NULL world"

Upvotes: 2

Yangguang
Yangguang

Reputation: 1785

you can try:

"hello '' ''world''".replace( /''\s*''/g,'\'\'');
//"hello ''world''"

Upvotes: 0

Related Questions