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'"
This question is related to
javascript
jquery
string
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"
var text = "http://example.com";
text = "'"+text+"'";
Would attach the single quotes (') to the front and the back of the string.
Try:
var text = "'" + "http://example.com" + "'";
I think, the best and easy way for you, to put value inside quotes is:
JSON.stringify(variable or value)
To represent the text below in JavaScript:
"'http://example.com'"
Use:
"\"'http://example.com'\""
Or:
'"\'http://example.com\'"'
Note that: We always need to escape the quote that we are surrounding the string with using \
JS Fiddle: http://jsfiddle.net/efcwG/
General Pointers:
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Example
var answer='It\'s alright';
var answer="He is called \"Johnny\"";
let's think urls = "http://example1.com http://example2.com"
function somefunction(urls){
var urlarray = urls.split(" ");
var text = "\"'" + urlarray[0] + "'\"";
}
output will be text = "'http://example1.com'"
In case of array like
result = [ '2015', '2014', '2013', '2011' ],
it gets tricky if you are using escape sequence like:
result = [ \'2015\', \'2014\', \'2013\', \'2011\' ].
Instead, good way to do it is to wrap the array with single quotes as follows:
result = "'"+result+"'";
var text = "\"http://www.example1.com\"; \"http://www.example2.com\"";
Using escape sequence of " (quote), you can achieve this
You can place singe quote (') inside double quotes without any issues Like this
var text = "'http://www.ex.com';'http://www.ex2.com'"
Lets assume you have a bunch of urls separated by spaces. In this case, you could do this:
function quote(text) {
var urls = text.split(/ /)
for (var i = 0; i < urls.length; i++) urls[i] = "'" + urls[i] + "'"
return urls.join(" ")
}
This function takes a string like "http://example.com http://blarg.test"
and returns a string like "'http://example.com' 'http://blarg.test'"
.
It works very simply: it takes your string of urls, splits it by spaces, surrounds each resulting url with quotes and finally combines all of them back with spaces.
This can be one of several solutions:
var text = "http://example.com";
JSON.stringify(text).replace('\"', '\"\'').replace(/.$/, '\'"')
Source: Stackoverflow.com