I am trying to extract a string from within a larger string where it get everything inbetween a :
and a ;
Current
Str = 'MyLongString:StringIWant;'
Desired Output
newStr = 'StringIWant'
This question is related to
javascript
regex
string
substring
You can also use this one...
function extractText(str,delimiter){_x000D_
if (str && delimiter){_x000D_
var firstIndex = str.indexOf(delimiter)+1;_x000D_
var lastIndex = str.lastIndexOf(delimiter);_x000D_
str = str.substring(firstIndex,lastIndex);_x000D_
}_x000D_
return str;_x000D_
}_x000D_
_x000D_
_x000D_
var quotes = document.getElementById("quotes");_x000D_
_x000D_
// " - represents quotation mark in HTML
_x000D_
<div>_x000D_
_x000D_
_x000D_
<div>_x000D_
_x000D_
<span id="at">_x000D_
My string is @between@ the "at" sign_x000D_
</span>_x000D_
<button onclick="document.getElementById('at').innerText = extractText(document.getElementById('at').innerText,'@')">Click</button>_x000D_
_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<span id="quotes">_x000D_
My string is "between" quotes chars_x000D_
</span>_x000D_
<button onclick="document.getElementById('quotes').innerText = extractText(document.getElementById('quotes').innerText,'"')">Click</button>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
@Babasaheb Gosavi Answer is perfect if you have one occurrence of the substrings (":" and ";"). but once you have multiple occurrences, it might get little bit tricky.
The best solution I have came up with to work on multiple projects is using four methods inside an object.
So enough talking, let's see the code:
var getFromBetween = {
results:[],
string:"",
getFromBetween:function (sub1,sub2) {
if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return false;
var SP = this.string.indexOf(sub1)+sub1.length;
var string1 = this.string.substr(0,SP);
var string2 = this.string.substr(SP);
var TP = string1.length + string2.indexOf(sub2);
return this.string.substring(SP,TP);
},
removeFromBetween:function (sub1,sub2) {
if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return false;
var removal = sub1+this.getFromBetween(sub1,sub2)+sub2;
this.string = this.string.replace(removal,"");
},
getAllResults:function (sub1,sub2) {
// first check to see if we do have both substrings
if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return;
// find one result
var result = this.getFromBetween(sub1,sub2);
// push it to the results array
this.results.push(result);
// remove the most recently found one from the string
this.removeFromBetween(sub1,sub2);
// if there's more substrings
if(this.string.indexOf(sub1) > -1 && this.string.indexOf(sub2) > -1) {
this.getAllResults(sub1,sub2);
}
else return;
},
get:function (string,sub1,sub2) {
this.results = [];
this.string = string;
this.getAllResults(sub1,sub2);
return this.results;
}
};
var str = 'this is the haystack {{{0}}} {{{1}}} {{{2}}} {{{3}}} {{{4}}} some text {{{5}}} end of haystack';
var result = getFromBetween.get(str,"{{{","}}}");
console.log(result);
// returns: [0,1,2,3,4,5]
var s = 'MyLongString:StringIWant;';
/:([^;]+);/.exec(s)[1]; // StringIWant
Use split()
var s = 'MyLongString:StringIWant;';
var arrStr = s.split(/[:;]/);
alert(arrStr);
arrStr
will contain all the string delimited by :
or ;
So access every string through for-loop
for(var i=0; i<arrStr.length; i++)
alert(arrStr[i]);
I used @tsds way but by only using the split function.
var str = 'one:two;three';
str.split(':')[1].split(';')[0] // returns 'two'
word of caution: if therre is no ":" in the string accessing '1' index of the array will throw an error! str.split(':')[1]
therefore @tsds way is safer if there is uncertainty
str.split(':').pop().split(';')[0]
If you want to extract all substrings from a string, that occur between two delimiters (different or same), you can use this function. It returns an array with all substrings found:
function get_substrings_between(str, startDelimiter, endDelimiter)
{
var contents = [];
var startDelimiterLength = startDelimiter.length;
var endDelimiterLength = endDelimiter.length;
var startFrom = contentStart = contentEnd = 0;
while(false !== (contentStart = strpos(str, startDelimiter, startFrom)))
{
contentStart += startDelimiterLength;
contentEnd = strpos(str, endDelimiter, contentStart);
if(false === contentEnd)
{
break;
}
contents.push( str.substr(contentStart, contentEnd - contentStart) );
startFrom = contentEnd + endDelimiterLength;
}
return contents;
}
// https://stackoverflow.com/a/3978237/1066234
function strpos(haystack, needle, offset)
{
var i = (haystack+'').indexOf(needle, (offset || 0));
return i === -1 ? false : i;
}
// Example usage
var string = "We want to extract all infos (essential ones) from within the brackets (this should be fun).";
var extracted = get_substrings_between(string, '(', ')');
console.log(extracted);
// output: (2) ["essential ones", "this should be fun"]
Orginally from PHP by raina77ow, ported to Javascript.
var str = '[basic_salary]+100/[basic_salary]';
var arr = str.split('');
var myArr = [];
for(var i=0;i<arr.length;i++){
if(arr[i] == '['){
var a = '';
for(var j=i+1;j<arr.length;j++){
if(arr[j] == ']'){
var i = j-1;
break;
}else{
a += arr[j];
}
}
myArr.push(a);
}
var operatorsArr = ['+','-','*','/','%'];
if(operatorsArr.includes(arr[i])){
myArr.push(arr[i]);
}
var numbArr = ['0','1','2','3','4','5','6','7','8','9'];
if(numbArr.includes(arr[i])){
var a = '';
for(var j=i;j<arr.length;j++){
if(numbArr.includes(arr[j])){
a += arr[j];
}else{
var i = j-1;
break;
}
}
myArr.push(a);
}
}
myArr = ["basic_salary", "+", "100", "/", "basic_salary"]
var number = 200
if (number >= 500 || number <= 600){
alert("your message");
}
This could be the possible solution
var str = 'RACK NO:Stock;PRODUCT TYPE:Stock Sale;PART N0:0035719061;INDEX NO:21A627 042;PART NAME:SPRING;';
var newstr = str.split(':')[1].split(';')[0]; // return value as 'Stock'
console.log('stringvalue',newstr)
You can also try this:
var str = 'one:two;three';
str.split(':').pop().split(';')[0]; // returns 'two'
function substringBetween(s, a, b) {
var p = s.indexOf(a) + a.length;
return s.substring(p, s.indexOf(b, p));
}
// substringBetween('MyLongString:StringIWant;', ':', ';') -> StringIWant
// substringBetween('MyLongString:StringIWant;;', ':', ';') -> StringIWant
// substringBetween('MyLongString:StringIWant;:StringIDontWant;', ':', ';') -> StringIWant
A small function I made that can grab the string between, and can (optionally) skip a number of matched words to grab a specific index.
Also, setting start
to false
will use the beginning of the string, and setting end
to false
will use the end of the string.
set pos1
to the position of the start
text you want to use, 1
will use the first occurrence of start
pos2
does the same thing as pos1
, but for end
, and 1
will use the first occurrence of end
only after start
, occurrences of end
before start
are ignored.
function getStringBetween(str, start=false, end=false, pos1=1, pos2=1){
var newPos1 = 0;
var newPos2 = str.length;
if(start){
var loops = pos1;
var i = 0;
while(loops > 0){
if(i > str.length){
break;
}else if(str[i] == start[0]){
var found = 0;
for(var p = 0; p < start.length; p++){
if(str[i+p] == start[p]){
found++;
}
}
if(found >= start.length){
newPos1 = i + start.length;
loops--;
}
}
i++;
}
}
if(end){
var loops = pos2;
var i = newPos1;
while(loops > 0){
if(i > str.length){
break;
}else if(str[i] == end[0]){
var found = 0;
for(var p = 0; p < end.length; p++){
if(str[i+p] == end[p]){
found++;
}
}
if(found >= end.length){
newPos2 = i;
loops--;
}
}
i++;
}
}
var result = '';
for(var i = newPos1; i < newPos2; i++){
result += str[i];
}
return result;
}
To get all substring.
var out = []; 'MyLongString:StringIWant;'
.replace(/(:)\w+(;)+/g, (e) => {
out.push(e.replace(':', '').replace(';', ''))
return e;
});
console.log(out[0])
You can use a higher order function to return a 'compiled' version of your extractor, that way it's faster.
With regexes, and compiling the regex once in a closure, Javascript's match will return all matches.
This leaves us with only having to remove what we used as our markers (ie: {{
) and we can use string length for this with slice.
function extract([beg, end]) {
const matcher = new RegExp(`${beg}(.*?)${end}`,'gm');
const normalise = (str) => str.slice(beg.length,end.length*-1);
return function(str) {
return str.match(matcher).map(normalise);
}
}
Compile once and use multiple times...
const stringExtractor = extract(['{','}']);
const stuffIneed = stringExtractor('this {is} some {text} that can be {extracted} with a {reusable} function');
// Outputs: [ 'is', 'text', 'extracted', 'reusable' ]
Or single-time use...
const stuffIneed = extract(['{','}'])('this {is} some {text} that can be {extracted} with a {reusable} function');
// Outputs: [ 'is', 'text', 'extracted', 'reusable' ]
Also look at Javascript's replace
function but using a function for the replacement argument (You would do that if for example you were doing a mini template engine (string interpolation) ... lodash.get could also be helpful then to get the values you want to replace with ? ...
My answer is too long but it might help someone!
I like this method:
var str = 'MyLongString:StringIWant;';
var tmpStr = str.match(":(.*);");
var newStr = tmpStr[1];
//newStr now contains 'StringIWant'
Get string between two substrings (contains more than 1 character)
function substrInBetween(whole_str, str1, str2){
if (whole_str.indexOf(str1) === -1 || whole_str.indexOf(str2) === -1) {
return undefined; // or ""
}
strlength1 = str1.length;
return whole_str.substring(
whole_str.indexOf(str1) + strlength1,
whole_str.indexOf(str2)
);
}
Note I use indexOf()
instead of lastIndexOf()
so it will check for first occurences of those strings
Using jQuery:
get_between <- function(str, first_character, last_character) {
new_str = str.match(first_character + "(.*)" + last_character)[1].trim()
return(new_str)
}
string
my_string = 'and the thing that ! on the @ with the ^^ goes now'
usage:
get_between(my_string, 'that', 'now')
result:
"! on the @ with the ^^ goes
Try this to Get Substring between two characters using javascript.
$("button").click(function(){
var myStr = "MyLongString:StringIWant;";
var subStr = myStr.match(":(.*);");
alert(subStr[1]);
});
Taken from @ Find substring between the two characters with jQuery
Source: Stackoverflow.com