How can i get html content with regExp? - javascript

var str = '<h2 id="test1">11</h2><h2 id="test2">22</h2>'
var arr1 = ["test1","test2"]
var arr2 = ["11","22"]
How can i get arr1/arr2 from str?

In real life, elements of your interest may be interleaved with other
elements, having also e.g. id attributes.
So the regex to get the text after id=" up to the next " may be not
enough.
The situation is even worse, when you want to retrieve the text content of
the element, especially if it contains its own child elements.
So in the case of HTML it is generally much easier and more natural to use
DOM methods and attributes, instead of regex.
You can e.g. create a DOM element and set its inner HTML (from your string).
Then, you can retrieve its child elements, e.g. by tag name and process them in
a loop.
Then (in the loop), having each current element, you can get either any its
attribute or inner text and push it into a respective array (created before).
So the example Javascript fragment, demonstrating the methods to use, can look like below:
<script>
var str = '<h2 id="test1">11</h2><h2 id="test2">22</h2>';
var el = document.createElement('div');
el.innerHTML = str;
var elems = el.getElementsByTagName('h2');
var arr1 = [], arr2 = [];
for (var i = 0; i < elems.length; i++) {
var currElem = elems[i];
arr1.push(currElem.getAttribute("id"));
arr2.push(currElem.innerText);
}
document.write('arr1: ' + arr1);
document.write('<br/>');
document.write('arr2: ' + arr2);
</script>
Of course, your final goal is not to write the arrays to the document, but make
of them any use you intend, so I wrote document.write only for demonstration purpose.

get your ids using the following regex
var str = '<h2 id="123"></h2><h2 id="123"></h2>';
var res = str.match(/(id="(.*?)(\"))/g);

You can use this code, it will return exact what you want.
<script type="text/javascript">
var str1 = '<h2 id="test1">11</h2><h2 id="test2">22</h2>';
var str2 = '<h2 id="test1">11</h2><h2 id="test2">22</h2>';
var pattern_id = /id=\"([a-zA-Z0-9-]+)\"/;
var pattern_value = /\>(\d+)\</;
var id_array = [];
var value_array = [];
do {
var array = str1.match(pattern_id);
if(array != null)
{
id_array.push(array[1]);
str1 = str1.replace(pattern_id, '');
}
}while(array != null);
do {
var array = str2.match(pattern_value);
if(array != null)
{
value_array.push(array[1]);
str2 = str2.replace(pattern_value, '');
}
}while(array != null);
console.log(id_array); // id are stored here ex: test1, test2
console.log(value_array); // value are stored here, 11, 22
</script>

Related

each & for loop mixed up my array order

I've created an associative array for index spaces inside a sentence for example:
sentence: hello how are you? (spaces between the word 'hello' to 'how')
so my array looks like this:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
but when I use 'for' loop its show me (using alert) the indexes 0,1,2,3 first and after them the sub-indexes, its mixed up my array order, any idea?
here my code:
function words_indexer(user_content)
{
var words_array = user_content.split(" ");
var indexed_words = {};
var word_counter = 0
var last_word_counter = 0
$.each(user_content, function(word_key,word_value){
if(word_value === ''){
var indexed_key = last_word_counter + '_' + word_key;
indexed_words[indexed_key] = word_value;
}else{
var indexed_key = word_counter;
indexed_words[indexed_key] = word_value;
last_word_counter = word_counter;
word_counter++;
}
});
for (var key in indexed_words) {
alert(key + ' ' + indexed_words[key]);
}
}
If your array index needs an extra level of structure then it may be better to just create a nested array instead:
indexed_words[0] = hello
indexed_words[0][1] = space
indexed_words[0][2] = space
indexed_words[0][3] = space
indexed_words[0][4] = space
indexed_words[0][5] = space
indexed_words[0][6] = space
indexed_words[0][7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
I believe adding an underscore to your array key may actually cause Javascript to consider it as being a string which would bump your numeric keys up above it.
You can't use non-numeric indexes for arrays in javascript (a_b is not considered numeric). For this you probably should use an object. And then loop through it like this:
for(var word_key in indexed_words) {
if(!indexed_words.hasOwnProperty(word_key)) continue;
var word_value = indexed_words[word_key];
// Your code
}

JavaScript - change font color on certain index

I have this long string and I want a part of it transformed into white colour using only JavaScript.
Example 1:
var string = document.getElementById("subtitle").innerHTML; //returns the string
var i = string.indexOf("("); //returns 80
var j = string.indexOf(")"); //return 93
Example 2: I can get the wanted text but I don't know how to change it white
var string = document.getElementById("subtitle").innerHTML; //returns the string
var i = string.indexOf("(");
var j = string.substring(i, string.indexOf(")")+1); //return the exact string I want to paint white
//j.paintWhite(); how?
I would like to paint all the characters between positions 80 and 93 (or selected as shown in example #2) white. How can I do it?
You need to create an html container for that text where you can specify a style attribute.
also, do not use the variable name string as it is reserved to the language
In order to do that, I would recommend using jQuery, as it is a bit easier.
But if you don't want to, you can do:
var text = document.getElementById("subtitle").innerHTML;
var cut = text.split("(");
var cut2 = cut[1].split(")");
var colored = cut[0] + '<span style="color:#fff;">('+cut2[0]+')</span>'+cut2[1];
document.getElementById("subtitle").innerHTML = colored;
if you assume "transformed into white colour" is doing
<span style="color:#fff">MY_TEXT_HERE</span>
then you could try the following with arrays:
var string = document.getElementById("subtitle").innerHTML;
var arr1 = string.split('(');
var arr2 = arr1[1].split(')');
var finalString = arr1[0] + '<span style="color:#fff">' + arr2[0] + '</span>' + arr2[1];
You must modify the inner Html of the element so it has a text element nested with a defind style.
http://jsfiddle.net/gsexxsbs/
var element = document.getElementById("subtitle");
var htmlText = element.innerHTML;
var i = htmlText.indexOf("(");
var j = htmlText.indexOf(")")+1;
var redText = htmlText.substring(i, j);
element.innerHTML = htmlText.substring(0,i)+"<a style='color:red;'>"+redText+"</a>"+htmlText.substring(j);

Display Blank array in console

I am using multi dimension array to store data. It working but when we print it in console it show blank array and under it its showing two array, it should be show only one array inside.
It should look like this.
ar['outbound']['Meal']="111,121"
and its look in console like this
It is printing undefined also and one more thing
how to remove "," from the last
Here is fiddle
Code
var ar = [];
ar['Outbound'] = [];
ar['Inbound'] = [];
var ch="";
var sr= [];
sr['Meal']= [];
sr['Lounge']= [];
$('a').click(function(){
ch = $(this).parent().find('.no').text();
var boundType= $(this).parent().find('.bound').text();
ar[boundType][$(this).parent().find('.service').text()] +=($(this).parent().find('.no').text()) + ","; console.log(ar)
})
To avoid "undefined" you have to set a default value to your array items:
if (!ar[boundType][service]) {
ar[boundType][service] = '';
}
And it's better to add ',' before adding a new value:
if (ar[boundType][service].length > 0) {
ar[boundType][service] += ',';
}
See demo: http://jsfiddle.net/AVU54/1/
The problem is here:
ar[boundType][$(this).parent().find('.service').text()] +=($(this).parent().find('.no').text()) + ",";
Replace that with:
var temp = $(this).parent().find('.service').text();
ar[boundType][temp] = (ar[boundType][temp] + "," || '') + ($(this).parent().find('.no').text());
This checks if the variable exists.
Also, arrays can't have strings as indexes. Use objects, instead:
var ar = {};
ar['Outbound'] = {};
ar['Inbound'] = {};
// etc...

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.

How to check first character in string and how to send that string into an array in Jquery?

friends.
I have an array and it contains some string values.
ex: array name="All_array"
Now i want to check all values in that array for first character of a string.
if a String starts with character 'a' then move that string to array called "A_array".
if a String starts with character 'b' then move that string to array called "B_array".
How to achieve this task.
var splitArrays = {};
for(var i = 0; i < All_array.length; ++i){
var firstChar = All_array[i].substr(0,1).toUpperCase();
if(!splitArrays[firstChar + '_array'])
splitArrays[firstChar + '_array'] = [];
splitArrays[firstChar + '_array'].push(All_array[i]);
}
This will take every element in All_array and put them into an object containing the arrays indexed by the first letter of the elements in All_array, like this:
splitArrays.A_array = ['Abcd','Anej','Aali']
etc...
Here's a fiddle: http://jsfiddle.net/svjJ9/
The code would be this:
for(var i=0; i<All_array.length; i++){
var firstChar = All_array[i].substr(0, 1).toUpperCase();
var arrayName = firstChar + "_array";
if(typeof(window[arrayName]) == 'undefined') window[arrayName] = []; //Create the var if it doesn't exist
window[arrayName].push(All_array[i]);
}
A_array = []; //empty the array (cause you wanted to 'move')
Hope this helps. Cheers
You could do it using each() and charAt:
$.each(All_array,function(i,s){
var c = s.charAt(0).toUpperCase();
if(!window[c + '_array']) window[c + '_array'] = [];
window[c + '_array'].push(s);
});

Categories