How to get string between single quotes in javascript

I have a string that looks like this: "the word you need is 'hello' ".

What's the best way to put 'hello' (but without the quotes) into a javascript variable? I imagine that the way to do this is with regex (which I know very little about) ?

Any help appreciated!

asked Sep 11, 2012 at 9:54

1

Use match():

> var s =  "the word you need is 'hello' ";
> s.match(/'([^']+)'/)[1];
"hello"

This will match a starting ', followed by anything except ', and then the closing ', storing everything in between in the first captured group.

answered Sep 11, 2012 at 9:57

How to get string between single quotes in javascript

João SilvaJoão Silva

86.7k28 gold badges148 silver badges152 bronze badges

5

http://jsfiddle.net/Bbh6P/

var mystring = "the word you need is 'hello'"
var matches = mystring.match(/\'(.*?)\'/);  //returns array

​alert(matches[1]);​

answered Sep 11, 2012 at 10:04

lolerloler

2,5141 gold badge19 silver badges30 bronze badges

If you want to avoid regular expressions then you can use .split("'") to split the string at single quotes , then use jquery.map() to return just the odd indexed substrings, ie. an array of all single-quoted substrings.

var str = "the word you need is 'hello'";
var singleQuoted = $.map(str.split("'"), function(substr, i) {
   return (i % 2) ? substr : null;
});

DEMO

CAUTION

This and other methods will get it wrong if one or more apostrophes (same as single quote) appear in the original string.

answered Sep 11, 2012 at 10:20

Often while coding using javascript, you would have come across the use of 'single' or "double" quotes for strings and would have wondered, if there is any real difference between the two and if there is, is there an advantage of using one type of quote over the other? This article is going to answer just that! Read on!

Table of Contents

  • Difference between the two quote styles
  • Choosing the right quoting style
  • Single vs Double Quotes - Pros and Cons
  • Parting Words

Difference between the two quoting styles

Both single (' ') and double (" ") quotes are used to represent a string in Javascript. Choosing a quoting style is up to you and there is no special semantics for one style over the other. Nevertheless, it is important to note that there is no type for a single character in javascript, everything is always a string!

'apple' === "apple"

Some of the other key points that both styles of quoting are as follows:

  • Whichever quoting style you open a string with, close it with the same style.
  • 'apple' //correct
    "apple" //correct
    "apple' //incorrect
    
  • The system doesn't care which one you use.
  • On German, Hungarian, Austrian, and many other keyboards, you have to use the Shift key for both single or double-quotes.
  • On Turkish Q keyboards, we need to press Shift for a single quote and not for a double quote!

Choosing the right quoting style

Wise selection of quoting can help you from escaping single (') or double(") quotes within a string. For example, if you wish to store a HTML snippet in a variable, you can use double quotes (") for HTML attribute values and use single quotes (') for enclosing the JavaScript string:

var div = '
...
'

Quote within a quote

Using quotations within a string gives rise to an error. for example,

var message='Javascript's beauty is simplicity';

There is no way for the browser to know which one is the closing quote. The interpreter sees the second quote in 'Javascript's as the ending quote - so the rest of the line becomes invalid.

We can fix this by using the fact that javascript allows both single and double quotes to define a string. So in this case you can go for double-quotes.

var message="Javascript's beauty is simplicity";

An alternate method is to escape quote arks using a forward slash "\". You use a forward slash in front of the character you intend to escape. So the same message becomes:

var message='Javascript\'s beauty is simplicity';

Points to remember

  • A double-quoted string can have single quotes without escaping them, conversely, a single-quoted string can have double quotes within it without having to escape them.
  •  Double quotes ( \" ) must escape a double quote and vice versa single quotes ( \' ) must escape a single quote.

Single vs Double Quotes - Pros and Cons

Pros

                      Single Quotes                                   Double Quotes
 Better readability for empty strings (' ') looks   better than ("" "")  In JSON the only quoting style allowed is double quotes (" ")
 Easier if you wish to write html within javascript  Eliminates the need to escape apostrophes when writing   sentences in english

Cons

    Single Quotes                                   Double Quotes
  Not supported by JSON   Must press an extra key (Shift)  when wanting to use double quotes

Combing through a few popular JavaScript projects we can see a clear preference for single quotes over double-quotes.

 Project  Dominant quote     style
 lodash   ' - 99% of quotes
 chalk   ' - 100% of quotes
 react   ' - 90% of quotes
 request   ' - 97% of quotes
 commander.js   ' - 97% of quotes
 moment   ' - 90% of quotes
 express   ' - 92% of quotes
 tslib   " - 100% of quotes
 debug   ' - 97% of quotes
 node-fs-extra   ' - 98% of quotes
 axios   ' - 81% of quotes

Data obtained from https://bytearcher.com/

However, a considerable number of front-end libraries prefer double quote style which might have to do with the presence of HTML fragments.

Parting words

To sum it up, try to stick with one quoting style throughout. If you are confused about which one to pick, go with the widely-used single quotes. In ES6, you also have a third option to enclose strings - the `backtick`string.

Can you use single quotes for strings in JavaScript?

Both single (' ') and double (" ") quotes are used to represent a string in Javascript. Choosing a quoting style is up to you and there is no special semantics for one style over the other.

How do you handle a single quote in JavaScript?

Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

Can you use single quotes for string?

Single-quoted Strings: It is the easiest way to define a string. You can use it when you want the string to be exactly as it is written. All the escape sequences like \r or \n, will be output as specified instead of having any special meaning. Single-quote is usually faster in some cases.

How do you strip quotes in JavaScript?

Use the String. replaceAll() method to remove all double quotes from a string, e.g. str. replaceAll('"', '') .