Adding quotes to a string in VBScript

2019-01-03 06:45发布

I have this code:

a = "xyz"  
g = "abcd " & a  

After running it, the value of g is abcd xyz.

However, I want quotes around the value of a in g. After running the code, g should be abcd "xyz" instead.

How can I accomplish this?

8条回答
Lonely孤独者°
2楼-- · 2019-01-03 07:00

You can escape by doubling the quotes

g="abcd """ & a & """"

or write an explicit chr() call

g="abcd " & chr(34) & a & chr(34)
查看更多
闹够了就滚
3楼-- · 2019-01-03 07:02

I designed a simple approach using single quotes when forming the strings and then calling a function that replaces single quotes with double quotes.

Of course this approach works as long as you don't need to include actual single quotes inside your string.

Function Q(s)

    Q = Replace(s,"'","""")

End Function

...

user="myself"
code ="70234"
level ="C"

r="{'User':'" & user & "','Code':'" & code & "','Level':'" & level & "'}"
r = Q(r)
response.write r

...

Hope this helps.

查看更多
放我归山
4楼-- · 2019-01-03 07:04

I found the answer to use double and triple quotation marks unsatisfactory. I used a nested DO...LOOP to write an ASP segment of code. There are repeated quotation marks within the string. When I ran the code:

thestring = "<asp:RectangleHotSpot Bottom=""" & bottom & """ HotSpotMode=""PostBack"" Left="""& left & """    PostBackValue=""" &xx & "." & yy & """ Right=""" & right & """ Top=""" & top & """/>"

the output was: <`asp:RectangleHotSpot Bottom="28

 'Changing the code to the explicit chr() call worked:

thestring = "<asp:RectangleHotSpot Bottom=""" & bottom & chr(34) & " HotSpotMode=""PostBack"" Left="""& left & chr(34) & " PostBackValue=""" &xx & "." & yy & chr(34) & " Right=""" & right & chr(34) & " Top=""" & top & chr(34) &"/>"

The output:

<asp:RectangleHotSpot Bottom="28" HotSpotMode="PostBack" Left="0" PostBackValue="0.0" Right="29" Top="0"/>
查看更多
我命由我不由天
5楼-- · 2019-01-03 07:05

I don't think I can improve on these answers as I've used them all, but my preference is declaring a constant and using that as it can be a real pain if you have a long string and try to accommodate with the correct number of quotes and make a mistake. ;)

查看更多
孤傲高冷的网名
6楼-- · 2019-01-03 07:09

The traditional way to specify quotes is to use Chr(34). This is error resistant and is not an abomination.

Chr(34) & "string" & Chr(34)
查看更多
劫难
7楼-- · 2019-01-03 07:13

You can do like:

a="""xyz"""  
g="abcd " & a  

Or:

a=chr(34) & "xyz" & chr(34)
g="abcd " & a  
查看更多
登录 后发表回答