Roo
Roo

Reputation: 11

VB - Replace Function and escaping a quote

I appreciate there are a lot of similar posts on here which I have read with interest, but I just can't find the solution for my particular issue, hope someone can help.

strFieldValue is a string (a title) which may contain quotes e.g. someone may put text like 9" (9 inch) - this causes issues for the code following this. So I wanted to search the string for the quote(s) and replace with escaped quotes. So far I have only managed to remove the quote altogether.

What I have tried -

newFieldValue = Replace(strFieldValue,Chr(34), "") - this removed the quote

newFieldValue = Replace(strFieldValue,Chr(34), """"") - I thought this would work as the double quotes would escape the one in the middle, but all it did was print all 5 quotes in my debug

Is there a way to make any quotes in the string 'safe' but still exist?

Many thanks Lisa

The data passed to the JSON scripts, which contains the offending string:

{"request":{},"results":[{"columns":[{"dbname":"REFERENCE","text":"Reference"},{"dbname":"VERSION","text":"Version"},{"dbname":"TITLE","text":"Title"},{"dbname":"AUTHOR","text":"Author"},{"dbname":"STATE","text":"State"}],"rows":[{"id":"6422","REFERENCE":"TPJ/TECH/DES/406","VERSION":"v1A","TITLE":"Doc Baselines Test lisa % && /","AUTHOR":"LISA CARVER","STATE":"Filed"}]}]}

{"request":{},"results":[{"columns":[{"dbname":"REFERENCE","text":"Reference"},{"dbname":"VERSION","text":"Version"},{"dbname":"TITLE","text":"Title"},{"dbname":"AUTHOR","text":"Author"},{"dbname":"STATE","text":"State"}],"rows":[{"id":"6422","REFERENCE":"TPJ/TECH/DES/406","VERSION":"v1A","TITLE":"Doc Baselines Test lisa" % && /","AUTHOR":"LISA CARVER","STATE":"Filed"}]}]}

The latter one is cutting the string short with the quote.

Upvotes: 1

Views: 1576

Answers (1)

William Hazelrig
William Hazelrig

Reputation: 11

This is likely too late to be any help to this poster, but JSON is JavaScript Object Notation, which means the language for which the quote needs to be escaped is JavaScript, rather than VB.Net. To escape a single or a double quote in JavaScript, you can replace it with a backslash followed by the single or double quote. That is a little tricky to write in a Regex -- and this becomes a much nastier problem in C#.Net because C# also uses backslash for escaping -- but this example should get you started:

Dim s AS String
s = "This is a ""quote"" test."
s = Regex.Replace(s,"[""]","\\""")

' After VB.Net quote-escaping and replacing the string-delimiting quote marks with the slashes more familiar to JavaScript users, that reduces to /["]/ (with an implicit global replace directive) for the pattern, and a string consisting of a backslash followed by a double-quote, for the replacement value.

Upvotes: 1

Related Questions