Using a function defined in a variable
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();">
精彩评论