Using a function defined in a variable - javascript

I found this code on another question, but am not sure how to use it:
var text = document.getElementById("text").innerHTML;
text = text.replace(/"z"/g,
function(n){ return ++n });
document.write(text);
It's exactly what I need, but I'm not sure how to pass a number to the function. Essentially, I have a large list of csv (comma delimited) items and need to look for each occurrence of "z" and replace it with a number incremented by one. The code is here, but I'm just not knowledgeable yet to know how to use it.
I've placed my text witch needs to be replaced inside of a div with an id of text. Any ideas?

Define a variable n before that code:
var n = 0;
Remove the n argument from the function, so you have
function(){ return ++n });
The n then refers to the variable you defined and the function requires no arguments.
The argument n was the matched text in the question you referenced. In this case, that text is irrelevant, as it is always z.
document.write is generally not a good idea. It would be better to replace it by assigning to the innerHTML of an element of your choice.

The value passed into the function in the variable n is what's been found in the string. That's a number in the question you've referenced but here it's text (the letter 'z'). Instead of using the text that was found you can just create a global variable and use that instead:
var text = document.getElementById("text").innerHTML;
var num = 0;
text = text.replace(/z/g, function(n){ return ++num });
document.write(text);
(Also note that you need to get rid of the quotes around the 'z' character).

If I read the code correctly. It takes the inner html from a single element with id=text.
e.g the span elements below:
<div id="text">
<span id="exzzzample">maybe CSV data is here z</span>
<span>More CSV Data z z z z</span>
</div>
It then replaces each z with a number that keeps incrementing. This would be:
<span id="ex123ample">maybe CSV data is here 4</span>
<span>More CSV Data 5 6 7 8</span>
The starting value of n can be set outside of this (the line before your code starts) with:
var n = 567; // An arbitrary starting value.
Note that any "z" in the attributes of contained elements will also be replaced as per my example. "z" should at least be very unique if you decide to solve your problem this way.

you need to fix the id of the element you're replacing the text into. This works:
<script>
var n = 0;
function replaceText() {
var text = document.getElementById("text").innerHTML;
text = text.replace(/"z"/g, function(){ return ++n });
// Changed to be placed here as suggested
document.getElementById("text").innerHTML = text;
}
</script>
<div id="text">
"6","z","AAA 101 - College 101:Student Experience","Introduces students to college culture and prepares...","1"
</div>
<input type="button" value="Find" onClick="replaceText();">

Related

Transfer random String to .innerHTML

I want to change the content of a div randomly by .InnerHTML. The text are saved as variables. The random number is another variable. The Problem is, that if I put text and random number together it will print text1 for example.
Can someone help me with that?
function switchText(){
var text1 = "hello";
var text2 = "there";
var text3 = "ObiWan";
var randomNumber = Math.floor(Math.random() * 3) + 1;//creates random No. from 1 - 3
document.getElementById("randomText").innerHTML = "text" + randomNumber;
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
How about storing all random strings in an array, like so:
function switchText(){
var randomWords = ["hello", "there", "ObiWan"];
var randomIndex = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
document.getElementById("randomText").innerHTML = randomWords[randomIndex];
//the problem
}
Actually you can access those variables by using index notation (it's described really nicely here) so in your specific case of function you just need to change the line where you try to access the variable to
document.getElementById("randomText").innerHTML = this['text' + randomNumber];
However though such notation is not something I would recommend. Usage of array as it was suggested is much more readable in fact.
Store those texts into an array and use the random number.
Get the random number as follow: Math.floor(Math.random() * 3)
function switchText(){
var texts = ["hello", "there", "ObiWan"];
var randomNumber = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[randomNumber];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
You can store those texts into an object as well.
function switchText() {
var texts = {
"text1": "hello",
"text2": "there",
"text3": "ObiWan"
};
var randomNumber = Math.floor(Math.random() * 3) + 1; //creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[`text${randomNumber}`];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
Your question is focused on how to dynamically construct a variable name, but usually this problem comes up because the solution you are attempting is based on a coding pattern that has boxed you into a corner. Instead of writing a potentially hazardous solution or one that is overly complex, re-think your approach.
Whenever you have several pieces of data to store that don't have key names to go with them, you should be storing those data in an Array. The advantages to storing data in an array are huge. So, you should place the strings into an array instead of individual variables that all have to have similar names. So, now you have less variables to worry about and no variable names that have to be set to certain values and the problem of dynamically creating a variable name is gone entirely.
All you need to do now is to use the random number as an index to the array. Don't adjust the random to make it 1-based, because arrays are 0-based. And, when you get the random, multiply it by the length of the array, rather than hard code a number. This way, all you have to do is add/remove strings to the array for them to become possible resulting strings.
This structure and solution make your code simpler and more flexible.
Also, don't set up your event handlers using HTML event attributes. There are many reasons why you shouldn't use this 25+ year old technique. Do it in JavaScript.
var strings = ["hello","there","ObiWan"]; // Store the possible strings in an array
var btn = document.getElementById("randomText"); // Get a reference to the trigger element
var output = document.getElementById("output"); // And the output area
// Set up the event handler in JavaScript, not HTML
btn.addEventListener("click", function(){
// Set the output to a string from the array using a random index
output.innerHTML = strings[Math.floor(Math.random() * strings.length)];
});
<button id="randomText">click here</button>
<div id="output"></div>

Add function to onclick with String parameter that contains HTML

I would like to add a function in an onclick with 3 parameters: int, int, string. The string parameter that contains an HTML and other quotations. Would it be possible?. I saw it here pass string but it is not working on my case.
<p onclick="myfunction(0,3,'<b">FirstName =
\"Dondellx\"\n<b>LastName</b> = \"Batacx\"\n<b>path</b> =
\"xxxpath\""');dondell
</p>
This function that contains the String with many \\ characters are actually from a JSON file which I put in a "p" tag in a loop when reading the JSON.
This is what i am doing to get the JSON item and put to the string param;
//This is a for loop
<p onclick="myfunction(0,3,'dataFromJSon[0]')"></p>
<p onclick="myfunction(0,3,'dataFromJSon[1]')"></p>
<p onclick="myfunction(0,3,'dataFromJSon[2]')"></p>
This is the text editor to enter my Text.
As you can see, I have quotations in the textArea, so that is why i need to save it with qoutations. :
This is the JSON:
Your html is misformed indeed, so I created a simpler demo. Hopefully it'll still be useful as I use an object to pass the html code as well as the other parameters.
var object = {a:0,b:3,c:'<b>FirstName=</b>Dondellx'};
function myfunction(obj){
document.getElementById("out").innerHTML=obj.c;
}
<p onclick="myfunction(object)">click</p>
<div id="out"></div>
This is certainly because there are so many syntax error in you HTML and JavaScript code.
Not correctly escape quote, not escape line break inside a javascript string declaration, HTML tag not properly close, attribute value not correctly defined...
Maybe try this (I have implement a fake myfunction for exemple and replace \n by <br/>, the line break not make sense in HTML).
function myfunction(a,b,str){
var row = document.createElement('div');
row.innerHTML = str;
document.body.appendChild(row);
}
<p onclick="myfunction(0,3,'<b>FirstName = "Dondellx&quot<br/><b>LastName</b> = "Batacx"<br/><b>path</b> = "xxxpath"');">dondell
</p>

How to find a substring only in the text portion of an HTML string, with Javascript?

UPDATE: I am no longer specifically in need of the answer to this question - I was able to solve the (larger) problem I had in an entirely different way (see my comment). However, I'll check in occasionally, and if a viable answer arrives, I'll accept it. (It may take a week or three, though, as I'm only here sporadically.)
I have a string. It may or may not have HTML tags in it. So, it could be:
'This is my unspanned string'
or it could be:
'<span class="someclass">This is my spanned string</span>'
or:
'<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>'
or:
'<span class="no-text"><span class="silly-example"></span></span><span class="some-class">This is my spanned string</span>'
I want to find the index of a substring, but only in the portion of the string that, if the string were turned into a DOM element, would be (a) TEXT node(s). In the example, only in the part of the string that has the plain text This is my string.
However, I need the location of the substring in the whole string, not only in the plain text portion.
So, if I'm searching for "span" in each of the strings above:
searching the first one will return 13 (0-based),
searching the second will skip the opening span tag in the string and return 35 for the string span in the word spanned
searching the third will skip the empty span tag and the openings of the two nested span tags, and return 91
searching the fourth will skip the nested span tags and the opening of the second span tag, and return 100
I don't want to remove any of the HTML tags, I just don't want them included in the search.
I'm aware that attempting to use regex is almost certainly a bad idea, probably even for simplistic strings as my code will be encountering, so please refrain from suggesting it.
I'm guessing I will need to use an HTML parser (something I've never done before). Is there one with which I can access the original parsed strings (or at least their lengths) for each node?
Might there be a simpler solution than that?
I did search around and wasn't been able to find anyone ask this particular question before, so if someone knows of something I missed, I apologize for faulty search skills.
The search could loop through the string char by char. If inside a tag, skip the tag, search the string only outside tags and remember partial match in case the text is matched partially then interrupted with another tag, continue the search outside the tag.
Here is a little function I came up with:
function customSearch(haysack,needle){
var start = 0;
var a = haysack.indexOf(needle,start);
var b = haysack.indexOf('<',start);
while(b < a && b != -1){
start = haysack.indexOf('>',b) + 1;
a = haysack.indexOf(needle,start);
b = haysack.indexOf('<',start);
}
return a;
}
It returns the results you expected based in your examples. Here is a JSFiddle where the results are logged in the console.
Let's start with your third example:
var desiredSubString = 'span';
var entireString = '<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
Remove all HTML elements from entireString, above, to establish textString:
var textString = entireString.replace(/(data-([^"]+"[^"]+")/ig,"");
textString = textString.replace(/(<([^>]+)>)/ig,"");
You can then find the index of the start of the textString within the entireString:
var indexOfTextString = entireString.indexOf(textString);
Then you can find the index of the start of the substring you're looking for within the textString:
var indexOfSubStringWithinTextString = textString.indexOf(desiredSubString);
Finally you can add indexOfTextString and indexOfSubStringWithinTextString together:
var indexOfSubString = indexOfTextString + indexOfSubStringWithinTextString;
Putting it all together:
var entireString = '<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
var desiredSubString = 'span';
var textString = entireString.replace(/(data-([^"]+"[^"]+")/ig,"");
textString = textString.replace(/(<([^>]+)>)/ig,"");
var indexOfTextString = entireString.indexOf(textString);
var indexOfSubStringWithinTextString = textString.indexOf(desiredSubString);
var indexOfSubString = indexOfTextString + indexOfSubStringWithinTextString;
You could use the browser's own HTML parser and XPath engine to search only inside the text nodes and do whatever processing you need.
Here's a partial solution:
var haystack = ' <span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
var needle = 'span';
var elt = document.createElement('elt');
elt.innerHTML = haystack;
var iter = document.evaluate('.//text()[contains(., "' + needle + '")]', elt).iterateNext();
if (iter) {
var position = iter.textContent.indexOf(needle);
var range = document.createRange();
range.setStart(iter, position);
range.setEnd(iter, position + needle.length);
// At this point, range points at the first occurence of `needle`
// in `haystack`. You can now delete it, replace it with something
// else, and so on, and after that, set your original string to the
// innerHTML of the document fragment representing the range.
console.log(range);
}
JSFiddle.

How do I create and increment a 2 or 3 digit hexadecimal number?

How do I increment the highest hexidecimal number from an array of hexidecimal numbers? My knowledge of hexidecimal is somewhat spotty so any help would be appreciated. And to be perfectly honest I don't know if the numbers are hexadecimal or not because there is a "u" in front of them but they look that way if you remove the "u". The values are from an InDesign snippet document.
Example:
var anArray = ["uf9","ufc","u111","u112","u136","u137"]; // actual values
var getUniqueID = getNextHigherNumber(anArray);
function getNextHigherNumber(anArray) {
// sort array
// create variable and add one
// return variable
return variable;
}
XML from the server (look at Self and Source):
<Hyperlink Self="ufc" Name="is a multiline hyperlink that terminates here" Source="uf9" Visible="false" Highlight="None" Width="Thin" BorderStyle="Solid" Hidden="false" DestinationUniqueKey="1">
<Properties>
<BorderColor type="enumeration">Black</BorderColor>
<Destination type="object">HyperlinkURLDestination/http%3a//test.com#1stMultilineLink/</Destination>
</Properties>
</Hyperlink>
<Hyperlink Self="u112" Name="hyperlink inline" Source="u111" Visible="false" Highlight="None" Width="Thin" BorderStyle="Solid" Hidden="false" DestinationUniqueKey="2">
<Properties>
<BorderColor type="enumeration">Black</BorderColor>
<Destination type="object">HyperlinkURLDestination/http%3a//test.com</Destination>
</Properties>
</Hyperlink>
<Hyperlink Self="u137" Name="another multline hyperlink" Source="u136" Visible="false" Highlight="Outline" Width="Thick" BorderStyle="Solid" Hidden="false" DestinationUniqueKey="3">
<Properties>
<BorderColor type="enumeration">Purple</BorderColor>
<Destination type="object">HyperlinkURLDestination/http%3a//google.com#multilinehyperlink</Destination>
</Properties>
</Hyperlink>
More background:
I have an existing XML document that looks like it's using hexidecimal number system for it's IDs and I need to be able to create a unique ID for new nodes. The ID values look similar to HTML web colors like, "0xFF0000" (which is red) but the difference is that it is using 2 or 3 characters instead of 6, for example, "ufc" or "u112".
I receive an XML file from the server and it has nodes and each node has an ID with a unique value (see XML example above). If I have to create a new "item" I need to create a unique ID for it that isn't already used.
First of all, hexadecimal is just a representation of a number.
The number itself remains the same.
Adding 2, means, take the value of this number, and add the value of 2.
Hexadecimal is just another way to write the number down.
Your effort of trying to figure out what these values are is highly appreciated, but why not check the documentation to know for sure?
You have an XML which you received with/from InDesign.
Just searching for that throws "IDML" at me, which seems to be the name Adobe gave to the format you are trying to parse.
Adobe provides a document describing this format:
https://wwwimages2.adobe.com/content/dam/Adobe/en/devnet/indesign/cs55-docs/IDML/idml-specification.pdf
Section 10.1.1 is about the Self attribute:
The Self attribute contains a unique identifier for the elements that
contain it. This identifier is used elsewhere in the IDML package to
refer to the element, as discussed in the “Object Reference
Format” section of this specification. Schema Example 2.
Self attribute Self { xsd:string }
As you can see, the value is a string, and not a number.
On page 31, you can find a description of how Adobe creates the values for Self including this statement:
The only requirement of the value of the Self attribute is that it is
unique within the IDML package. If you are writing the IDML yourself,
you do not need to observe the above pattern— you can change the value
of the Self attribute to anything you want as long as it is unique
(within the IDML package) and as long as all references to the element
are also changed to match.
I think that you complicate things when thinking hexadecimal ;) You can just convert your hex values to decimal ones and then continue what you are doing, so you can do like this :
var anArray = ['u112', 'u136', 'uf9', 'u137', 'u111', 'ufc'];
var getUniqueID = getNextHigherNumber(anArray);
trace('u', getUniqueID); // gives : u138
function getNextHigherNumber(anArray:Array):String {
var max:int = 0;
for(var i:int = 0; i<anArray.length; i++){
// convert the hex value to an integer
var num:int = int('0x' + String(anArray[i]).substr(1));
// get the max value
if(num > max) max = num;
}
// return the hex value of (max value + 1)
return (max + 1).toString(16);
}
Hope that can help.
You tagged both JavaScript and ActionScript (I don't know ActionScript), but the code in your question looks like JavaScript to me, and the other answer in here looks like it is in ActionScript; so, assuming you still want to do this (looks like user null is onto something), I will post the JavaScript equivalent:
var anArray = ["uf9","ufc","u111","u112","u136","u137"];
function getNextHigherNumber(theArray) {
var maxNum = 0;
theArray.forEach(function(num) {
num = parseInt(num.substr(1), 16);
if(num > maxNum) maxNum = num;
});
return 'u' + (maxNum + 1).toString(16);
}
// Run the function to see if it works
console.log(getNextHigherNumber(anArray));
What it does inside the forEach function/loop:
Remove the "u" from each array element.
Convert the string without the "u" to its int decimal equivalent.
Store the number in maxNum if the current number is bigger than the previous stored maxNum.
And then it returns the biggest number plus one, converted back again to hex via .toString(16) (and prepending an 'u' to it).

Detect html tag on a string, get the value and remove values inside html tag in javascript

I have a String which contains HTML tags:
var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
And i also have a form with hidden input:
<input type='hidden' name='id' value=''>
With that String above, i want to get the value inside <p> tag which is 1 and assign that value to hidden input. And after that, i wanted to remove all the HTML tag inside the string which are these <br><p>1</p><em>My First Javascript</em>. So therefore the only value of str will be Hello World.
Is there any way how to do this on Javascript or jquery?
Thanks guys!
So, what you want to be doing is to convert your string into a jQuery object. You can do so like this -
var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
var $holder = $('<div>');
$holder.append(str);
Now we have your string encapsulated within another div element. Next we extract the value within the <p> element -
var value = $holder.find('p').text(); // 1
Now that we have that value we can place it into the hidden input field -
$('input[name="id"]').val(value);
Now to remove all other elements from the original string - we'll use the container we created earlier for this -
$.each($holder.children(),function(index,elem){
$(elem).remove();
});
Now we can take the textual contents of $holder with $holder.text() and it should be just -
Hello World
If you would like to fiddle with this,
you can do so here - http://jsfiddle.net/TVXbw/1/
Ok, a quick and simple way:
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = str;//where str is the html string, obviously...
var pTagValue = tmpDiv.getElementsByTagName('p')[0].innerHTML;//=== '1'
document.getElementById('yourInputId').value = pTagValue;
If I understood correctly, that's what you're after, right?

Categories