Jquery: Replace values from one array to another - javascript

I have 2 arrays that have the exact same number of keys. I would like to loop through the first array, then search <p> tags for any matching values. Then if a match is found, I would like to replace that matching value with the corresponding value from the 2nd array.
I have this for now:
var text_original = ["original_word1", "original_word2", "original_word3"];
var text_replaced = ["replaced_word1","replaced_word2","replaced_word3"];
var z;
for (z = 0; z <= text_original.length; ++z) {
$("p").each(function(){
var text=jQuery(this).html();
$(this).html(text.replace(text_original,text_replaced));
});
}
This is the general idea, I'm getting confused how to isolate the single values from the multiple array values. Thanks in advance for help!

Use the function indexOf and check for the found text.
Use the function text rather than the function html.
var text_original = ["original_word1", "original_word2", "original_word3"];
var text_replaced = ["replaced_word1", "replaced_word2", "replaced_word3"];
$('p').each(function() {
var text = $(this).text();
var index = text_original.indexOf(text);
if (index > -1) $(this).text(text.replace(text_original[index], text_replaced[index]));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>original_word1</p>
<p>original_word2</p>
<p>Ele from SO</p>
Why $.text()?
The HTML <p> element represents a paragraph of text. Paragraphs are usually represented in visual media as blocks of text that are separated from adjacent blocks by vertical blank space and/or first-line indentation. Paragraphs are block-level elements.
The function $.text() will return the text without HTML tags.

You missing echo before json_encode().
Your json_encode() should not be wrapped into quotes.
You have to use [z] to access to an element of an array.
Code :
var text_original = <?php echo json_encode($text_original); ?>;
var text_replaced = <?php echo json_encode($text_replaced); ?>;
var z;
for (z = 0; z <= text_original.length; ++z) {
$("p").each(function(){
var text=jQuery(this).html();
$(this).html(text.replace(text_original[z],text_replaced[z]));
});
}

Related

Finding index in array based on DIV text

I have a DIV which has text in it:
<div id="x">
divText
</div>
I have a "header row" like this:
var headerRow = ["wrong","wrongAgain","divText"];
I also have an array like this:
var theArray = [["blah","blah","0"]["notIt","blahblah","1"],["unrelated","dontLook","0"]];
I want to find the index in theArray (2) based on the text within the div:
var theDiv = x.innerHTML;
for (i=0; i < headerRow.length; i++){
if (headerRow[i] == theDiv){ <--never works
if (headerRow[i] == x.innerHTML) { <---never works
if (headerRow[i] == "divText") { <--works (i = 2)
}
How can I find the index based on the innerHTML of a div / variable (first two cases above)? Thanks!
You are using innerHTML where as which returns content of HTML element including spaces and new lines.Instead use innerText or use methods trim method on either innerHTML or textContent.
In your case the comparision is not successful because the text that you are extracting using innerHTML contains spaces and newline.
Note:If element ID is valid identifier it can be used directly as
window.elementid or just elementid but it's best practice to use getElementByID
var x = document.getElementById('x')
var theDiv = x.innerHTML.trim();
for (i=0; i < headerRow.length; i++){
if (headerRow[i] == theDiv) {
// your codes goes here
console.log('works')
}
}
or You can use
var theDiv = x.innerText
or
var theDiv = x.textContent.trim()
<div id="x">
divText
</div>
<script>
var headerRow = ["wrong","wrongAgain","divText"];
var theDiv = document.getElementById('x').innerHTML;
console.log(theDiv);
for (i=0; i < headerRow.length; i++){
if (headerRow[i] == theDiv.trim()){
console.log(headerRow.indexOf(headerRow[i]));
console.log(i);
}
}
</script>
Your if comparison doesn't work because of extra whitespace/new line in the div's innerHTML text. Thus you need to trim the string before comparing it with the contents of the header row array. Note that you can either use the indexOf method to get the index of the matching element, or you can just use the current value of i, which would also correspond to the index of that element. Hope this makes sense to you.
To get the text from div you should get element by id first
var theDiv = document.getElementById("x").innerHTML
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
It will work with 1sth array, and the 2nd nested array can be flattened first
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

javascript parse text from <a href> links

Lets say I have
ThisTextChanges
ThisTextChanges
ThisTextChanges
ThisTextChanges
I want to iterate through these and get the "ThisTextChanges" which are some numbers that changes, most accurately timers.
How can i achieve that? jquery is fine.
They are inside a div with id "main_container".
I need to put the text in a var so the href is importanto to know which var i use for each one.
Lets break the task down into several steps:
Get a handle to all of our links (document.querySelectorAll)
learn how to get the current text of an a tag (childNode[0].nodeValue)
put it all together (Array.from, Array.map)
Get a handle to all of our links:
we will use document.querySelectorAll to get list of all nodes that match our selector. here I'm just going to use the selector a, but you probably have a class that specifies these links vs other links on the page:
var links = document.querySelectorAll('a');
Get the text of a link
This one is a bit more complicated. There are several ways to do this, but one of the more efficient ways is to loop through the child nodes (which will mostly be text nodes), and append the node.nodeValue for each one. We could probably get away with just using the nodeValue of the first child, but instead we'll build a function to loop through and append each.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
Put it all together
To put it all together we will use Array.map to turn each link in our list into the text inside it. This will leave us with an array of strings. However in order to be able to pass it to Array.map we will have to have an array, and document.querySelectorAll returns a NodeList instead. So to convert it over we will use Array.from to turn our NodeList into an array.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
var linkTexts = Array.from(document.querySelectorAll('a'))
.map(getText);
console.log(linkTexts);
this is text
this is some more text
You can just add condition in the a selector as follows:
var array = [];
$('#main_container a[href="/example2"]').each(function(){
array.push($(this).html());
});
console.log(array);
You can iterate and store them in an Array
var arr = [];
$("a").each(function(){
arr.push($(this).text());
console.log( arr );
});
you can achieve that in may ways. this example using for loop.
var main_container = document.getElementById("main_container");
var items = main_container.getElementsByTagName("a");
for (var i = 0; i < items.length; ++i) {
// do something.....
}
var array = [];
$('#main_container a').each(function(){
array.push($(this).html());
});
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main_container">
ThisTextChanges 1
ThisTextChanges 2
ThisTextChanges 3
ThisTextChanges 4
</div>
Please try:
$('#main_container > a[href]').each(function() {
var tes = $(this).attr('href').substring(1);
window[tes] = $(this).text();
});
123 will produce var named example1 with value 123, and so on.

jQuery: create html elements from comma separated string?

I'm trying to create HTML elements (div's) from a comma separated string using jQuery.
Lets say I have a string that looks like this:
options ="some texts, another text, some more text";
and I need to create something like this:
<div>some texts</div>
<div>another text</div>
<div>some more text</div>
I first split the comma separated string like so:
var str = options;
var temp = new Array();
temp = str.split(", ");
And then I need to create the div's after this function which I have no idea how to do this.
Could someone please advise on this?
Try this:
var options ="some texts, another text, some more text";
var temp = options.split(", "); // first split string and convert it to array
var str = '';
$.each(temp, function(i,v) { // loop through array
str += "<div>"+v+"</div>"; // create html string and store it in str variable
});
$("body").append(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
You can do something like this using jQuery
var options = "some texts, another text, some more text";
var temp = options.split(", ");
// iterate and generate array of jQuery elements
var divs = temp.map(function(txt) {
// generate div using jQuery with text content as array element
return $('<div/>', {
text: txt
})
})
// update html content, use `append()` if you want to append instead of replacing entire content
$('body').html(divs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You don't need to convert to an array- just replace the commas and associated spaces with a closing div and opening div tag and then add an opening one to start with and a closing one to end with and you have the html structure.
var options ="some texts, another text, some more text";
var temp = "<div>" + options.replace(/, /g,"</div><div>") + "</div>;
//this will give: <div>some texts</div><div>another text</div><div>some more text</div>
$("body").append(temp);
Assuming you want the text interpreted as text, not HTML, you'll want to loop over the array your code gives you and create elements individually, like this:
var options = "some texts, <another> text, some more text";
options.split(", ").forEach(function(opt) {
$("<div>").text(opt).appendTo(document.body);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Note that I changed one of your entries to demonstrate the importance of ensuring they're treated as text, not HTML.
About your code:
var str = options;
var temp = new Array();
temp = str.split(", ");
The call to new Array() is completely unnecessary there, because you're overwriting the value of your temp variable on the very next line. split returns an array, it doesn't fill in one that it magically reaches out and grabs from the left-hand side of the assignment. :-) (There's also no reason to do var str = options; Just use options directly.)
Try this:
<div id="main-div"></div>
<script type = "text/javascript">
var options ="some texts, another text, some more text";
options.split(',').forEach(function(item){
$("#main-div").append("<div>"+item+"</div>");
});
</script>
var str = options;
var temp = str.split(", ").map(function(strOption) {
return '<div>' + strOption + '</div>';
}).join('');
myHTMLElement.innerHTML = $(temp);

Getting the innerhtml of td from string [JS]

Lets say I have the following string:
var string = "<td>123</td><td>asd</td>";
I want to take the values of the td's and put them in an array. I tried using the foreach function but my regex stops after the first closing td and gets everything between < and >.
var regex = '<([^<> ]*)([^<>]*)?>([^>]*)<\/([^<>]*)>';
var string = "<td>123</td><td>asd</td>";
var result = string.match(regex);
result.forEach(function($var){
console.log($var);
});
Output:
<td>123</td>
td
undefined
123
td
I need to manipulate the values so I can work directly in the foreach function without first splitting to an array.
Can I make this work with a regex? I can't use jQuery or append the string to the html.
Using regex alone to parse DOM is a no-no. However..
If you don't have nested <td> you can use the following code to get an array of values:
var string = "<td>123</td><td>asd</td>";
var tds = string.split("</td>");
var values = [];
for(var i=0; i<tds.length-1; i++){ //last element is empty if you split like this
values.push(tds[i].substr(4)); //ommit the "<td>"
}
alert(values);
More complex structures could be a problem and I would advise you to break the TDs up to separate ones and then extract the values using regex (/<td>(.*)</td>/g and select group 1). But for this example it works fine.
jsFiddle
Split the string with any of <td> OR </td> and reject the "".
This will work for you
var string = "<td>123</td><td>asd</td>";
var contents = string.split(/<td>|<\/td>/);
contents = contents.filter(function(el){return el != ""})
console.log(contents) //["123","asd"]
Do not parse HTML using RegExp!
Here is a jQuery version for your problem:
$("<tr/>").append("<td>123</td><td>asd</td>") // build a row with the cells
.find("td") // get the cells
.map(function() { return $(this).text(); }); // for each cell, get the content
Result: ["123", "asd"]
Edit: I see you can't use jQuery, that's unfortunate because you really need a DOM parser, and jQuery is just elegant and can do much more.
You could try the below code,
> var re = /[^<>]+(?=<\/)/g;
undefined
> var result = string.match(re);
undefined
> result.forEach(function($var){
... console.log($var);
... });
123
asd
> console.log(result);
[ '123', 'asd' ]
Explanation:
[^<>]+ Matches any character not of < or > one or more times.
(?=<\/) Lookahead asserts that anything following must be </
Avoid parsing HTML/XML with regex!
I figured out a plain way with JavaScript to do it:
function extractValues(code)
{
var tr = document.createElement('tr');
tr.innerHTML = code;
var tds = values.getElementsByTagName('td');
var values = [];
for (var i = 0; i < tds.length; i++) {
values.push(tds[i].innerHTML);
}
return values;
}
console.log(extractValues("<td>123</td><td>asd</td>"));
If you realy realy want a regex, use this:
/<td>((?:.(?!<\/td>))*.?)<\/td>/g

how to loop though div and get each value

I am trying to figure out how to get each value within my div. I am using
var cart = $('.basic-cart-cart-node-title.cell').text();
It is giving the results of OI-01OP-01OS-10-5SOR-04OR-05
I need to view them one by one: OI-01, OP-01, OS-10-5S, OR-04 OR-05.
So that I can match them against another field.
If you care to help me further, I have another div on the page:
var ParNum = $('.assess-title').text();
I would like to compare the values returned from the var cart and see if that value is in the ParNum. If it is there, I would like to apply a class.
Any help would be greatly appreciated.
Thanks!
You can store the values in an array using .map() method:
var values = $('.basic-cart-cart-node-title.cell').map(function() {
return $.trim( $(this).text() );
}).get();
For checking existence of the ParNum value in the array:
var does_exist = values.indexOf(ParNum) > -1;
Try this to iterate over elements:
var text = '';
$('.basic-cart-cart-node-title.cell').each(function (i, div) {
text += ' ' + $(div).text();
});
or this to get an array of matching div elements:
var divs = $('.basic-cart-cart-node-title.cell').toArray();
for (var i = 0; i < divs.length; i++) {
// $(div).text();
}
Reason for this is that $('.basic-cart-cart-node-title.cell') returns all div's at once, and you need to loop through the result. More specifically, $(selector) returns a so-called "wrapped set". It can be used to access each matching element (as I've shown above) or it can be used to apply any other jQuery function to the whole set at once. More info here.
var text = "";
$('.basic-cart-cart-node-title.cell').each(function(){
text += $(this).text() + ", ";
});
// remove the last ", " from string
text = text.substr(0, text.length -2);
var cart = [];
$('.basic-cart-cart-node-title.cell').each(function {
cart.push($(this).text());
}
This performs the matching and class adding you mentioned in the question.
var ParNum = $('.assess-title').text();
$('basic-cart-cart-node-title.cell').each(function () {
if ($(this).text() == ParNum) {
$(this).addClass("someclass");
}
}
You should try using
var cart ='';
$('.basic-cart-cart-node-title'.find('.cell').each(function()
{
cart = cart + $(this).val();
});
Hope it works for you.
var cart = $('.basic-cart-cart-node-title.cell').text().match(/.{5}/g);
This will give you an array with items 5 chars long. Regexes arent very fast, but a loop might be slower
Or easier to read, and in a string with commas:
var cart = $('.basic-cart-cart-node-title.cell').text(); // get text
cart = cart.match(/.{1,5}/g); // split into 5 char long pieces
cart = cart.join(",",); join on comma

Categories

Resources