{"id":22590,"date":"2023-01-27T15:54:17","date_gmt":"2023-01-27T10:24:17","guid":{"rendered":"https:\/\/java2blog.com\/?p=22590"},"modified":"2023-01-27T15:54:17","modified_gmt":"2023-01-27T10:24:17","slug":"get-string-between-two-characters-javascript","status":"publish","type":"post","link":"https:\/\/java2blog.com\/get-string-between-two-characters-javascript\/","title":{"rendered":"Get String Between Two Characters in JavaScript"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Using_substring_Method\">Using substring() Method<\/a><\/li><li><a href=\"#Using_slice_Method\">Using slice() Method<\/a><\/li><li><a href=\"#Using_split_Method\">Using split() Method<\/a><\/li><li><a href=\"#Using_substr_Method\">Using substr() Method<\/a><\/li><\/ul><\/div>\n<blockquote><p>\n<span style=\"font-size: 1.2em\">&#x1f4a1;<\/span><strong>TL;DR<\/strong><br \/>\n<strong>Use the `substring()` method to get String between two characters in JavaScript.<\/strong><\/p>\n<pre code='JavaScript' title='Use substring() Method'>\r\nfunction getSubstring(str, start, end) {\r\n  char1 =  str.indexOf(start) + 1;\r\n  char2 =  str.lastIndexOf(end);\r\n  return str.substring(char1, char2);\r\n}\r\nlet originalString = \"Hello,World!\";\r\nlet substring = getSubstring(originalString, ',', '!');\r\nconsole.log(substring); \r\n<\/pre>\n<pre title='OUTPUT'>\r\nWorld\r\n<\/pre>\n<p>Here, we got String between `,` and `!` in above example.\n<\/p><\/blockquote>\n<h2><span id=\"Using_substring_Method\">Using <code>substring()<\/code> Method<\/span><\/h2>\n<p><strong>Use the <code>substring()<\/code> method to extract a substring that is between two specific characters from the given string in JavaScript.<\/strong><\/p>\n<pre code=\"JavaScript\" title=\"Use substring() Method\">\r\nlet str = \"This is a sample string\";\r\nconsole.log(str.substring(1, 3));\r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nhi\r\n<\/pre>\n<p>The <code>substring()<\/code> method allows us to specify a <code>start<\/code> and <code>end<\/code> index for the substring we want to extract. Note that in JavaScript, <code>string<\/code> indices start from <code>0<\/code>, so the 2nd character is at index <code>1<\/code>, and the 4th character is at index <code>3<\/code>.<\/p>\n<p>The above example used <code>substring()<\/code> to display characters from the specified string. Here, <code>1<\/code> is passed as the first argument to specify the starting position of the substring, and the second argument, <code>3<\/code>, represents the substring&#8217;s ending position. So, the substring <code>hi <\/code> was returned between index <code>1<\/code> and <code>3<\/code>. Let&#8217;s see another example below:<\/p>\n<pre code=\"JavaScript\" title=\"Use substring() Method\">\r\nlet str = \"This is a sample string\";\r\nconsole.log(str.substring(2)); \r\nconsole.log(str.substring(4, 1)); \r\nconsole.log(str.substring(0, 1)); \r\nconsole.log(str.substring(-3));\r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nis is a sample string\r\nhis\r\nT\r\nThis is a sample string\r\n<\/pre>\n<p>Here, we can observe that in the first <code>console<\/code> statement, we passed only the starting position of the string to get all characters of the string starting from index <code>2<\/code> up to the end.<\/p>\n<p>In the second <code>console<\/code> statement, the start-index was greater than the end-index <code>(4,1)<\/code>. So here, the <code>substring()<\/code> method itself swapped the parameters as <code>(1,4)<\/code> and gave results accordingly. And <code>str.substring(0, 1)<\/code> was only used to get the string&#8217;s first character.<\/p>\n<p>We can observe that the last <code>console<\/code> statement index at the start was <code>-3<\/code> (less than <code>0<\/code>). So, in that case, the substring started from index <code>0<\/code> to the end. Consider another example below:<\/p>\n<pre code=\"JavaScript\" title=\"Use substring() Method\">\r\nlet str = \"This is a sample string\";\r\nlet startChar = \"a\";\r\nlet endChar = \"g\";\r\nlet startIndex = str.indexOf(startChar);\r\nlet endIndex = str.indexOf(endChar);\r\nlet substring = str.substring(startIndex, endIndex);\r\nconsole.log(substring);\r\n<\/pre>\n<pre title=\"OUTPUT\">\r\na sample strin\r\n<\/pre>\n<p>In this example, we first declared a string <code>str<\/code> with the value <code>This is a sample string<\/code>. And then, two variables, <code>startChar<\/code> and <code>endChar<\/code>, were declared, representing the two characters we wanted to use as the boundaries for our substring. And <code>indexOf()<\/code> method was used to find the index of the first occurrence of each of these characters in the string.<\/p>\n<p>Next, we used the <code>substring()<\/code> method to extract the substring between these two indexes. In this case, <code>a sample strin<\/code> substring was returned.<\/p>\n<p><strong>Note<\/strong>: The above solution assumes that the first character <code>a<\/code> is guaranteed to be present, and the second character <code>g<\/code> is also guaranteed to be present after the first character.<\/p>\n<p>The substring that was returned depends on the position of the characters in the string, so if the characters we are searching for are not in the string or are in the wrong order, it will return an empty string or an error. Also, if the <code>startChar<\/code> is the same as the <code>endChar<\/code> and the string contains multiple instances of <code>startChar<\/code>, it will return the substring between the first and second occurrence of <code>startChar<\/code>.<\/p>\n<p>For better understanding, create a function <code>getSubstring()<\/code> to get a substring between two characters from the given string. This function <code>getSubstring()<\/code> takes in three arguments:<\/p>\n<ul>\n<li><code>str<\/code> is the original string from which we want to extract a substring.<\/li>\n<li><code>start<\/code> is the starting character of the substring.<\/li>\n<li><code>end<\/code> is the ending character of the substring.<\/li>\n<\/ul>\n<pre code=\"JavaScript\" title=\"Use substring() Method\">\r\nfunction getSubstring(str, start, end) {\r\n  char1 =  str.indexOf(start) + 1;\r\n  char2 =  str.lastIndexOf(end);\r\n  return str.substring(char1, char2);\r\n}\r\nlet originalString = \"Hello,World!\";\r\nlet substring = getSubstring(originalString, ',', '!');\r\nconsole.log(substring); \r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nWorld\r\n<\/pre>\n<p>Using the <code>indexOf()<\/code> method, we can determine the position of a value in a string based on the first occurrence, as learned above. On the other hand, the <code>lastIndexOf()<\/code>  method returns the position of a value in a string based on the last occurrence.<\/p>\n<p>In the <code>getSubstring()<\/code> function definition, <code>char1<\/code> contained the index of the first character. And, <code>char2<\/code> contained the index of the second character.<\/p>\n<p><strong>Note<\/strong>:  <code>1<\/code> is added to the result of the <code>indexOf()<\/code> method because we do not want to include the first character <code>,<\/code> in the substring we want to get. However, there is no need to exclude <code>1<\/code> from the <code>lastIndexOf()<\/code> result because the character at the given end index is already omitted by <code>substring()<\/code>. <\/p>\n<p>Some important points:<\/p>\n<ul>\n<li>\n<p>In JavaScript, if you&#8217;re using the <code>indexOf()<\/code> or <code>lastIndexOf()<\/code> method to find a substring within a string, and the given values do not exist in the string, both methods will return <code>-1<\/code>, indicating that the substring was not found. <\/p>\n<\/li>\n<li>\n<p>If the first character of the substring does not exist in the string, <code>substring()<\/code> will return all the characters from the start to the last occurrence of the second character. Let&#8217;s see the below example to check this:<\/p>\n<\/li>\n<\/ul>\n<pre code=\"JavaScript\" title=\"Use substring() Method\">\r\nconst string1 = 'hello:to my;World;of JavaScript!';\r\nconst result = getSubstring(string1, '-', ';');\r\nconsole.log(result); \r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nhello:to my;World\r\n<\/pre>\n<p>Here, <code>-<\/code> was not present in <code>string1<\/code>. That&#8217;s why it returned substring from the start to the last occurrence of the <code>;<\/code>. Similarly, if the second character is absent, the entire string from the start to the first instance of the first character will be included in the substring. Consider the below example to check this:<\/p>\n<pre code=\"JavaScript\" title=\"Use substring() Method\">\r\nconst string1 = 'hello:to my;World;of JavaScript!';\r\nconst result = getSubstring(string1, ':', '-');\r\nconsole.log(result); \r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nhello:\r\n<\/pre>\n<h2><span id=\"Using_slice_Method\">Using <code>slice()<\/code> Method<\/span><\/h2>\n<p><strong>Use the <code>slice()<\/code> method to extract a substring that is between two specific characters from the given string in JavaScript.<\/strong><\/p>\n<pre code=\"JavaScript\" title=\"Use slice() Method\">\r\nlet str = \"Hello to my javaScript world!\";\r\nlet substring = str.slice(1, 4);\r\nconsole.log(substring); \r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nell\r\n<\/pre>\n<p>The <code>slice()<\/code> method in JavaScript can extract a substring from a string. This method takes two arguments: The substring&#8217;s starting index and ending index.<\/p>\n<p>The above code snippet returned the substring  <code>ell<\/code> between the 2nd and 4th characters of the given string. We can also use the <code>slice()<\/code> method with only one argument; it will slice the string from the given starting index until the end of the string. Check the below example:<\/p>\n<pre code=\"JavaScript\" title=\"Use slice() Method\">\r\nlet str = \"Hello to my javaScript world!\";\r\nlet substring = str.slice(9);\r\nconsole.log(substring);\r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nmy javaScript world!\r\n<\/pre>\n<p>The above example returned substring <code>my javaScript world!<\/code> using the <code>slice()<\/code> method from index <code>9<\/code> to the end of the string.<\/p>\n<p>Suppose <code>str.indexOf()<\/code> returned <code>-1<\/code> due to the absence of the required character in the string. In that case, we will increment the value by <code>1<\/code>, which results in <code>0<\/code> and allows us to extract characters from the beginning of the string. Check the below example to see how to do this:<\/p>\n<pre code=\"JavaScript\" title=\"Use slice() Method\">\r\nconst originalStr = \"Hello to my javaScript, world!\";\r\nconst  str= originalStr.slice( \r\n    originalStr.indexOf('-') + 1,\r\n    originalStr.lastIndexOf(',') );\r\nconsole.log(str);  \r\n <\/pre>\n<pre title=\"OUTPUT\">\r\nHello to my javaScript\r\n<\/pre>\n<p>In this code, <code>-<\/code> was not present in <code>originalStr<\/code>. So, <code>originalStr.indexOf(&#039;-&#039;) <\/code> returned <code>-1<\/code>; we then added <code>1<\/code>, and the start index became <code>0<\/code>. That&#8217;s why we got the string <code>Hello to my javaScript<\/code> from the start until we got the second character&#8217;s (<code>,<\/code>) last occurrence`.<\/p>\n<p>Consider a string, <code>Hello to my javaScript, world!<\/code> and extract a substring between <code>m<\/code> and <code>!<\/code> using the <code>slice()<\/code> method:<\/p>\n<pre code=\"JavaScript\" title=\"Use slice() Method\">\r\nlet str = \"Hello to my javaScript, world!\";\r\nlet substring = str.slice(str.indexOf(\"m\")+1,str.indexOf(\"!\"));\r\nconsole.log(substring); \r\n<\/pre>\n<pre title=\"OUTPUT\">\r\ny javaScript, world\r\n<\/pre>\n<p>The above code found the index of the first character <code>m<\/code> and then added <code>1<\/code> to it as we wanted to exclude it from the substring. In the same way, it found the index of the second character <code>!<\/code> and then extracted the substring <code>y javaScript, world<\/code> between these two indexes.<\/p>\n<section class=\"read-more-posts\">\n<div class=\"rm-header\">\n<h2>Further reading:<\/h2>\n<\/div>\n<div class=\"rm-wrap\">\n<div class=\"rm-item\">\n<h5><a href=\"https:\/\/java2blog.com\/add-character-to-string-in-javascript\/\" target=\"_blank\" rel=\"noopener\">Add character to String in Javascript<\/a><\/h5>\n<div class=\"ex\">\n\t\t\t<a href=\"https:\/\/java2blog.com\/add-character-to-string-in-javascript\/\" target=\"_blank\" rel=\"noopener\">Read more \u2192<\/a>\n\t\t<\/div>\n<\/div>\n<div class=\"rm-item\">\n<h5><a href=\"https:\/\/java2blog.com\/get-nth-character-string-javascript\/\" target=\"_blank\" rel=\"noopener\">Get Nth Character in String in JavaScript<\/a><\/h5>\n<div class=\"ex\">\n\t\t\t<a href=\"https:\/\/java2blog.com\/get-nth-character-string-javascript\/\" target=\"_blank\" rel=\"noopener\">Read more \u2192<\/a>\n\t\t<\/div>\n<\/p><\/div>\n<\/div>\n<\/section>\n<h2><span id=\"Using_split_Method\">Using <code>split()<\/code> Method<\/span><\/h2>\n<p><strong>We can also use the <code>split()<\/code> method to extract a substring between two specific characters in a string; you will need first to split the string into an array of substrings using the first character as the separator to retrieve the desired substring from the resulting array.<\/strong><\/p>\n<pre code=\"JavaScript\" title=\"Use split() Method\">\r\nlet str = \"Hi,Javascript is my favourite\";\r\nlet substrings = str.split(\",\");\r\nlet substring = substrings[1].substring(0,4);\r\nconsole.log(substring); \r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nJava\r\n<\/pre>\n<p>In JavaScript, the <code>split()<\/code> method is used to split a string into an array of substrings. It can take one or two arguments: A separator (string or regular expression)  and a limit.<\/p>\n<p>In this code, we used the <code>split()<\/code> method to split the string <code>Hi, Javascript is my favourite<\/code> into the array of substrings <code>[&quot;Hi&quot;, &quot;Javascript is my favourite&quot;]<\/code>, then we get the 2nd element from the array as <code>substrings[1]<\/code> which is <code>Javascript is my favourite<\/code>. After that, we extracted the first four characters, our desired substring <code>Java<\/code>.<\/p>\n<p>Now, let&#8217;s extract the last element of the string using the <code>Array.pop()<\/code> method:<\/p>\n<pre code=\"JavaScript\" title=\"Use split() Method\">\r\nlet str = \"Hi,Javascript is my favourite\";\r\nlet substrings = str.split(',').pop()\r\nconsole.log(substrings); \r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nJavascript is my favourite\r\n<\/pre>\n<p>Here, the <code>split()<\/code> method is used to split <code>str<\/code> into the array having two substrings, and then the <code>Array.pop()<\/code> method is used to remove and return the last element of the array, which is <code>Javascript is my favourite<\/code>.<\/p>\n<h2><span id=\"Using_substr_Method\">Using <code>substr()<\/code> Method<\/span><\/h2>\n<p><strong>Use the <code>substr()<\/code> method in JavaScript to extract a substring from a given string.<\/strong><\/p>\n<pre code=\"JavaScript\" title=\"Use substr() Method\">\r\nlet str = \"Hello,to my world of JavaScript!\";\r\nlet sub = str.substr(12, 5); \r\nconsole.log(sub);\r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nworld\r\n<\/pre>\n<p>The <code>substr()<\/code> method takes two parameters: the starting index of the substring and the length representing the number of characters we want to extract. <\/p>\n<p>In the above example, the <code>substr()<\/code> method was used to extract the substring <code>world<\/code> from the string <code>Hello, to my world of JavaScript!<\/code>. Here, we wanted to get a substring from index <code>12<\/code> having <code>5<\/code> characters. <\/p>\n<p>Consider a scenario where we want to get only the first character of the string:<\/p>\n<pre code=\"JavaScript\" title=\"Use substr() Method\">\r\nlet myStr = \"Hello,to my world of JavaScript!\";\r\nlet my_subStr = myStr.substr(0, 1);\r\nconsole.log(my_subStr);\r\n<\/pre>\n<pre title=\"OUTPUT\">\r\nH\r\n<\/pre>\n<p>We can observe first character <code>H<\/code> from <code>myStr<\/code> was returned because we have passed <code>0<\/code> as the starting index and <code>1<\/code> as the length of the substring. And if you want to get only the last character of the string, then the following solution is for you:<\/p>\n<pre code=\"JavaScript\" title=\"Use substr() Method\">\r\nlet myStr = \"Hello,to my world of JavaScript!\";\r\nlet my_subStr = myStr.substr(-1, 1);\r\nconsole.log(my_subStr);\r\n<\/pre>\n<pre title=\"OUTPUT\">\r\n!\r\n<\/pre>\n<p>In the above code snippet, <code>-1<\/code> was used as the starting index because we wanted to extract the substring from the end with a <code>1<\/code> character. Now, let&#8217;s extract the last <code>11<\/code> characters of <code>myStr<\/code>.<\/p>\n<pre code=\"JavaScript\" title=\"Use substr() Method\">\r\nlet myStr = \"Hello,to my world of JavaScript!\";\r\nlet my_subStr = myStr.substr(-11, 11);\r\nconsole.log(my_subStr);\r\n<\/pre>\n<pre title=\"OUTPUT\">\r\n JavaScript!\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsUsing substring() MethodUsing slice() MethodUsing split() MethodUsing substr() Method &#x1f4a1;TL;DR Use the `substring()` method to get String between two characters in JavaScript. function getSubstring(str, start, end) { char1 = str.indexOf(start) + 1; char2 = str.lastIndexOf(end); return str.substring(char1, char2); } let originalString = &#8220;Hello,World!&#8221;; let substring = getSubstring(originalString, &#8216;,&#8217;, &#8216;!&#8217;); console.log(substring); World Here, we [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":22693,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[42],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/22590"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=22590"}],"version-history":[{"count":4,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/22590\/revisions"}],"predecessor-version":[{"id":22690,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/22590\/revisions\/22690"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/22693"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=22590"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=22590"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=22590"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}