Javascript str.search() multiple instances - javascript

How can I retrieve multiple indexes from multiple instances of a string search?
var str = "food";
var index1 = str.search("o"); // 1
var index2 = str.search("o"); // ?
Thanks much,
Wen

I think the best way to do this for strings of non-trivial length is the RegExp.exec() function:
var str = "Foooooooood!",
re = /o/g,
match;
while (match = re.exec(str)) {
console.log(match.index); // logs 1 through 9
}

You can use second parameter of indexOf method to achieve what you want:
var str = "food",
index1 = str.indexOf("o"),
index2 = str.indexOf("o", index1+1);

Related

javascript get substring between two sets of characters

I have the following string:
var myString = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>';
how can i get with the least code the someExtraStuff.fileExt section?
should i do indexOf {{appName}} and then until the next "/> ?
You could search for the pattern {{appName}} and take all characters who are not quotes. Then take the second element of the match.
var string = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>',
substring = (string.match(/\{\{appName\}\}([^"]+)/) || [])[1]
console.log(substring);
You can do this with three methods
// 1 option
For single match
var regex = /\{\{appName\}\}([^"]+)/;
var myString = '<p class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/>';
console.log(myString.match(regex)[1]);
// 2 option
For multiple matches
var regex = /\{\{appName\}\}([^"]+)/g;
var myString = '<p class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/>';
var temp;
var resultArray = [];
while ((temp = regex.exec(myString)) != null) {
resultArray.push(temp[1]);
}
console.log(resultArray);
// 3 option For indexOf
var firstIndex= myString.indexOf("{{appName}}");
var lastIndex =firstIndex+ myString.substring(firstIndex).indexOf('"/>')
var finalString = myString.substring(firstIndex,lastIndex).replace("{{appName}}","");
console.log(finalString);

Extracting specific information from an array

I have data two sets of data as follows:
"One.Two.Three.Four"
"One.Two.Three.1.Four"
The first three parts are fixed and the remaining can extend to as many as possible.
I am trying to build an object where I want to split and combine whatever is present after three into an object.
var split = samplestr.split('.');
var finalarray = [];
if(split.length>4)
{
finalarray[0] = split[0];
finalarray[1] = split[1];
finalarray[2] = split[2];
finalarray[3] = split[3]+"."split[4];
}
I need to generalise this such that even if the string is of the form
"One.Two.Three.1.2.3.Four"
finalarray[3] = 1.2.3.Four;
Any hints on generalising this?
With Array#shift and Array#join.
var split = samplestr.split('.');
var finalarray = [];
if(split.length > 4) {
finalarray[0] = split.shift();
finalarray[1] = split.shift();
finalarray[2] = split.shift();
finalarray[3] = split.join(".");
}
simply replace
finalarray[3] = split[3]+"."split[4];
with
finalarray[3] = split.slice(3).join(".");
Split the string, slice the first part and append the join'ed second part:
console.info=function(x){document.write('<pre>'+JSON.stringify(x,0,3)+'</pre>')}
//--
var str = "One.Two.Three.Four.More.Stuff";
var s = str.split('.');
var result = s.slice(0, 3).concat(s.slice(3).join('.'));
console.info(result);

Get split number and string from string

I have an array of string like below:
var array =[];
array.push("Complex12");
array.push("NumberCar1");
array.push("Protect5");
I want to split the string and number of each item.
var Id = parseInt(array[0].match(/\d/g));
var type = array[0].replace(/\d+/g, '');
But I only get Id = 1(I want 12) and type = "Complex", where am I wrong?
thanks
I think you just missed + in first regexp
var Id = parseInt(array[0].match(/\d+/g));
Do it in one pattern with capture groups:
var mystr = "Complex12";
if (m = mystr.match(/^([a-z]+)([0-9]+)$/i)) {
var type = m[1];
var id = m[2];
}

JavaScript get character in sting after [ and before ]

I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));

Find text between two characters and for each, do something

I have a file full with text in the following format:
(ignoring the fact that it is CSS) I need to get the string between the two | characters and each time, do something:
<div id="unused">
|#main|
#header|
.bananas|
#nav|
etc
</div>
The code I have is this:
var test_str = $('#unused').text();
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
//I want to do something with each string here
This just gets the first string. How can I add logic in there to do something for each string?
You can use split method to get array of strings between |
Live Demo
arr = $('#unused').text().split('|');
You can split like
var my_splitted_var = $('#unused').text().split('|');
One way;
$.each($("#unused").text().split("|"), function(ix, val) {
val = $.trim(val); //remove \r|\n
if (val !== "")
alert(val);
});
One way :
var test_str = $('#unused').text();
while(!test_str.indexOf('|'))
{
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
test_str = test_str.slice(end_pos,test_str.length);
}
RegExp-Version:
LIVE DEMO (jsfiddle.net)
var trimmedHtml = $("#unused").html().replace(/\s/g, '');
var result = new Array();
var regExp = /\|(.+?)(?=\|)/g;
var match = regExp.exec(trimmedHtml);
result.push(match[1]);
while (match != null) {
match = regExp.exec(trimmedHtml);
if (match != null) result.push(match[1]);
}
alert(result);
So you only get the elements BETWEEN the pipes (|).
In my example I pushed every matching result to an array. You can now iterate over it to get your result.

Categories