[javascript] 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:


This question is related to javascript jquery string

The answer is

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:


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

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

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


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)

You can add these single quotes with template literals:

var text = "http://example.com"_x000D_
var quoteText = `'${text}'`_x000D_

Docs are here. Browsers that support template literals listed here.

To represent the text below in JavaScript:






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:

  • You can use quotes inside a string, as long as they don't match the quotes surrounding the string:


var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
  • Or you can put quotes inside a string by using the \ escape character:


var answer='It\'s alright';
var answer="He is called \"Johnny\"";
  • Or you can use a combination of both as shown on top.


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'"

You can escape " with \

var text="\"word\"";


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(/.$/, '\'"')

Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with jquery tag:

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.? How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) Only on Firefox "Loading failed for the <script> with source" How to prevent page from reloading after form submit - JQuery Vue component event after render How to use jQuery Plugin with Angular 4? How to disable a ts rule for a specific line? Bootstrap 4 File Input How to force reloading a page when using browser back button? Datatables Select All Checkbox Unable to preventDefault inside passive event listener Getting Error "Form submission canceled because the form is not connected" How to create multiple page app using react Set height of chart in Chart.js console.log(result) returns [object Object]. How do I get result.name? Setting and getting localStorage with jQuery JQuery: if div is visible Using OR operator in a jquery if statement Deprecation warning in Moment.js - Not in a recognized ISO format How to use aria-expanded="true" to change a css property DataTables: Cannot read property style of undefined Disable Chrome strict MIME type checking Consider marking event handler as 'passive' to make the page more responsive Cannot open local file - Chrome: Not allowed to load local resource "Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project what is right way to do API call in react js? why $(window).load() is not working in jQuery? How to use JQuery with ReactJS $(...).datepicker is not a function - JQuery - Bootstrap remove first element from array and return the array minus the first element How to use a jQuery plugin inside Vue Uncaught SyntaxError: Invalid or unexpected token jquery 3.0 url.indexOf error How to redirect page after click on Ok button on sweet alert? Content Security Policy: The page's settings blocked the loading of a resource Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document' Checkbox value true/false vue.js 'document.getElementById' shorthand Removing legend on charts with chart.js v2

Questions with string tag:

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript How to change the datetime format in pandas How to write to a CSV line by line? convert string to number node.js "error: assignment to expression with array type error" when I assign a struct field (C) Remove 'b' character do in front of a string literal in Python 3 Ruby: How to convert a string to boolean What does ${} (dollar sign and curly braces) mean in a string in Javascript? How do I make a new line in swift converting json to string in python PHP - remove all non-numeric characters from a string C# - How to convert string to char? How can I remove the last character of a string in python? Converting std::__cxx11::string to std::string How to convert string to date to string in Swift iOS? Convert time.Time to string TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3 How can I capitalize the first letter of each word in a string using JavaScript? Best way to verify string is empty or null Hive cast string to date dd-MM-yyyy Check for special characters in string How to convert any Object to String? Print "\n" or newline characters as part of the output on terminal Set the maximum character length of a UITextField in Swift How do I convert a Python 3 byte-string variable into a regular string? What does $ mean before a string? Delete the last two characters of the String Splitting a string into separate variables Figure out size of UILabel based on String in Swift Matching strings with wildcard How do I concatenate strings? Print very long string completely in pandas dataframe Check string for nil & empty Convert float to string with precision & number of decimal digits specified? How do I print my Java object without getting "SomeType@2f92e0f4"? enum to string in modern C++11 / C++14 / C++17 and future C++20 How should I remove all the leading spaces from a string? - swift Convert array to JSON string in swift Swift extract regex matches Convert a file path to Uri in Android How would I get everything before a : in a string Python