Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put quotes around a variable string in JavaScript

I have a JavaScript variable:

var text = "http://example.com"

Text can be multiple links. How can I put '' around the variable string?

I want the strings to, for example, look like this:

"'http://example.com'"
like image 932
re1man Avatar asked Mar 15 '12 06:03

re1man


People also ask

How do you put quotes in a string variable?

Use a formatted string literal to add double quotes around a variable in Python, e.g. result = f'"{my_var}"' . Formatted string literals let us include variables inside of a string by prefixing the string with f .

How do you quote a string in JavaScript?

If you have single quotes in the string, delimit it with double quotes. If you have double quotes in the string, delimit it with single quotes. If you need to use both types in the string, escape whatever delimiter you have chosen by prefixing it with a \ .

How do you display quotes in JavaScript?

Strings are created by putting data inside the quotes. JavaScript and other programming languages allow the users to keep the data either in double quotes (" ") or single quotes (' ').

How do you pass a string with a quote?

To do what you require you need to escape the single/double quotes within the name string. To do that you could use a regex: name = name. replace(/([\""|\''])/g, '\\$1'); $("#trID").


2 Answers

var text = "\"http://example.com\""; 

Whatever your text, to wrap it with ", you need to put them and escape inner ones with \. Above will result in:

"http://example.com"
like image 126
Sarfraz Avatar answered Oct 22 '22 07:10

Sarfraz


var text = "http://example.com";

text = "'"+text+"'";

Would attach the single quotes (') to the front and the back of the string.

like image 33
Ajai Avatar answered Oct 22 '22 06:10

Ajai