javascript/jquery to replace text conditionally with random text from an array - javascript

I would like to replace a string with a random string from an array if that string equals a certain condition.
So far I have this (which doesn't address the condition part).
the html:
<div>
<span class ="test">foo</span>
</div>
<div>
<span class ="test">bar</span>
</div>
<div>
<span class ="test">test</span>
</div>
<div>
<span class ="test">random</span>
</div>
the code:
$(".test").each(function () {
var quotes = new Array("foo", "bar", "baz", "chuck"),
randno = quotes[Math.floor(Math.random() * quotes.length)];
$('.test').text(randno);
});
This sets every ".test" class the same thing. I get:
foo
foo
foo
foo
or
bar
bar
bar
bar
How do I make this only replace the string if it equals say "foo"?
If I have multiple "foos" How do i get each "foo" it replaces to be random not all set to the same thing?

You need to use this in the .each() callback method
$(".test").each(function() {
var quotes = new Array("foo", "bar", "baz", "chuck"),
randno = quotes[Math.floor(Math.random() * quotes.length)];
//Check condition
if ($(this).text() === "foo") {
$(this).text(randno);
}
});
Alternatively you can also use .text(function)
var quotes = new Array("foo", "bar", "baz", "chuck");
$(".test").text(function(_, text) {
var randno = quotes[Math.floor(Math.random() * quotes.length)];
//Check condition
if (text === "foo") {
return randno;
}
return text;
});
$(function() {
var quotes = new Array("foo", "bar", "baz", "chuck");
$(".test").text(function(_, text) {
var randno = quotes[Math.floor(Math.random() * quotes.length)];
//Check condition
if (text === "foo") {
return randno;
}
return text;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="test">foo</span>
</div>
<div>
<span class="test">bar</span>
</div>
<div>
<span class="test">test</span>
</div>
<div>
<span class="test">random</span>
</div>

Another approach is to shuffle the replacements array, than use it:
/* Famous shuffle function */
Array.prototype.shuffle = function() {
for (var j, x, i = this.length; i; j = Math.floor(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
$.fn.extend({
randomReplace: function(text, replacements) {
replacements.shuffle();
return this.each(function () {
if( $(this).text().toLowerCase()==text.toLowerCase() )
$(this).text(replacements.pop());
});
}
});
$('.test').randomReplace('foo', ['one', 'two', 'three', 'four', 'five', 'six']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="test">foo</span>
<span class="test">bar</span>
<span class="test">foo</span>
<span class="test">foo</span>
<span class="test">bar</span>

Related

Why function 'runFunc("keyboard", "mouse")' change only three Classes

In this code, I made a function runFunc(previousClass, newClass) for changing class but only three classes changes by clicking a button. Why should we click button three times to change all the classes.
<div class="parent_class" id="parent">
<div class="keyboard">1</div>
<div class="keyboard">2</div>
<div class="keyboard">3</div>
<div class="keyboard">4</div>
<div class="keyboard">5</div>
<div class="keyboard">6</div>
</div>
<br><br>
<button onclick="runFunc('keyboard', 'mouse')">Change Class</button>
<script>
var a;
function runFunc(previousClass, newClass) {
var i;
var a1 = typeof previousClass;
var a2 = typeof newClass;
if (a1 === "string" && a2 === "string") {
var a = document.getElementsByClassName(previousClass);
console.log(a);
for ( i = 0; i < a.length; i++ ) {
a[i].className = newClass;
}
var b = document.getElementsByClassName(newClass);
console.log(b);
console.log("\n\n")
}
}
</script>
</body>
It's because when you are replacing classname in first element it's automatically removed from the list, so the "old" second element become now first, but your loop advances forward and skips "old" second element and so on.
So what you can do is simply keep changing classname in first element until the list is empty:
var a;
function runFunc(previousClass, newClass) {
var i;
var a1 = typeof previousClass;
var a2 = typeof newClass;
if (a1 === "string" && a2 === "string") {
var a = document.getElementsByClassName(previousClass);
console.log(a);
while (a.length)
{
a[0].className = newClass;
}
var b = document.getElementsByClassName(newClass);
console.log(b);
console.log("\n\n")
}
}
<div class="parent_class" id="parent">
<div class="keyboard">1</div>
<div class="keyboard">2</div>
<div class="keyboard">3</div>
<div class="keyboard">4</div>
<div class="keyboard">5</div>
<div class="keyboard">6</div>
</div>
<br><br>
<button onclick="runFunc('keyboard', 'mouse')">Change Class</button>

How to check for specific object key and update if exists

I have text inputs that are writing to a model. I want those objects to write to the model and update if the key exists.
For example: If I submit,
Id: "1", Value: "Foo"
And I update it with a new value:
Id: "1", Value: "Bar"
My array should read:
0 { Id: "1", Value: "Bar"}
Not
0 { Id: "1", Value: "Foo"}
1 { Id: "1", Value: "Bar"}
Example here: JSFiddle
<div id="wrapper">
<div>
<input id="1" type="text" value="input_1">
<button>Button 1</button>
</div>
<br>
<div>
<input id="2" type="text" value="input_2">
<button>Button 2</button>
</div>
<br>
<div>
<input id="3" type="text" value="input_3">
<button>Button 3</button>
</div>
<br>
</div>
jQuery -- will add to the array but not sure how to update if key exists. Looked at other examples but still not getting it
var obj = {
pairs: []
}
$("button").on("click", function() {
var keyValuePairs = {
id: "",
value: ""
}
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
if(obj.pairs.length > 0){
$.each(obj.pairs, function(i, pair) {
if($(this).id !== input_id){
obj.pairs.push(keyValuePairs);
return false;
} else {
obj.pairs.splice(i, 1);
obj.pairs.push(keyValuePairs);
}
});
} else {
obj.pairs.push(keyValuePairs);
}
keyValuePairs.id = input_id;
keyValuePairs.value = dynamic_value;
console.log(obj);
});
Try this https://jsfiddle.net/y6rgm7z8/93/
$(document).ready(function() {
var obj = {
pairs: []
}
$("button").on("click", function() {
var keyValuePairs = {
id: "",
value: ""
}
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
var pair = obj.pairs.find(item => item.id === input_id)
if(pair){
pair.value = dynamic_value;
} else {
keyValuePairs.id = input_id;
keyValuePairs.value = dynamic_value;
obj.pairs.push(keyValuePairs);
}
console.log(obj);
});
});
The find() method executes the function once for each element present in the array:
If it finds an array element where the function returns a true value, find() returns the value of that array element (and does not check the remaining values)
Otherwise it returns undefined
The find() is better for performance than each().
And we don't need splice() with push() for updating because after find() we have link to the object, so we can change the value.
If find() returns undefined we will push the new object to the array
See if this helps
$(document).ready(function() {
var obj = {
pairs: []
}
$("button").on("click", function() {
var found = false;
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
var keyValuePairs = {
id: input_id,
value: dynamic_value
}
if(obj.pairs.length > 0){
$.each(obj.pairs, function(i, pair) {
if(pair[Object.keys(pair)[0]] === input_id){
obj.pairs[i] = keyValuePairs;
found = true;
return false;
}
});
if(!found)
obj.pairs.push(keyValuePairs);
} else {
obj.pairs.push(keyValuePairs);
}
console.log(obj);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div>
<input id="1"type="text" value="input_1">
<button>Button 1</button>
</div>
<br>
<div>
<input id="2" type="text" value="input_2">
<button>Button 2</button>
</div>
<br>
<div>
<input id="3" type="text" value="input_3">
<button>Button 3</button>
</div>
<br>
</div>
I finally changed a lot...
I used a flag to know if the update was done...
So I run the .each() loop first. It doesn't run if there is no key/pair already. Then a comparison if the change was not yet done, to push a new value.
var obj = {
pairs: []
}
$("button").on("click", function() {
var keyValuePairs = {
id: "",
value: ""
}
var change_done=false;
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
$.each(obj.pairs, function(i, pair) {
if(obj.pairs[i].id == input_id){ // Change is here.
obj.pairs[i].id=input_id;
obj.pairs[i].value=dynamic_value;
change_done=true;
return false;
}
});
if(!change_done || obj.pairs.length == 0){
obj.pairs.push(keyValuePairs);
}
keyValuePairs.id = input_id;
keyValuePairs.value = dynamic_value;
console.log(obj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div>
<input id="1 "type="text" value="input_1">
<button>Button 1</button>
</div>
<br>
<div>
<input id="2" type="text" value="input_2">
<button>Button 2</button>
</div>
<br>
<div>
<input id="3" type="text" value="input_3">
<button>Button 3</button>
</div>
<br>
</div>
I have rewritten a bit. If ID exists, its value will be updated and new row will not be inserted:
$(document).ready(function() {
var obj = {
pairs: []
}
$("button").on("click", function() {
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
var isUpdated = false;
var keyValuePairs = {
id: input_id,
value: dynamic_value
};
if (obj.pairs.length == 0) {
obj.pairs.push(keyValuePairs);
return false;
}
$.each(obj.pairs, function(i, pair) {
if (obj.pairs[i].id === input_id) {
obj.pairs[i].value = dynamic_value;
isUpdated = true;
return false;
}
});
if (!isUpdated) {
obj.pairs.push(keyValuePairs);
}
console.log(obj);
});
});
Tested and it works.
You can do it like this:
const pair = obj.pairs.find(pair => pair.id === input_id);
if (pair) {
obj.pairs[input_id] = {...keyValuePairs}
} else {
obj.pairs.push(keyValuePairs)
}

Javascript: Replace 'x' only if it is the first word of a text, not anywhere else

I'm working on a simple JS code to replace some words with others in a text using an array.
<textarea id="text1">
e mi e
ke fo
e di
</textarea>
<button type="button" onclick="myFunction()">try</button>
<pre id="demo"></pre>
<script>
function myFunction() {
var str = document.getElementById("text1").value;
var mapObj = {
"k":"g",
" e": "B",
"e":"ar"
};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.toLowerCase().replace(re, function(matched){
return mapObj[matched];
});
document.getElementById("demo").innerHTML = str;
}
</script>
The result is:
ar mi B
gar fo
ar di
But I desire to have this:
B mi B
gar fo
B di
If "e"s are to be changed before " e"s (separated e with a space before it), then " e"s will not be " e" but "ar", so in the array, I've put " e" above "e" and it works well.
However the problem is that the text may contain a separated "e" as the first word of the whole text or as the first word of a line with no space before it. When it's the case how can I replace this separated "e"with "B" and prevent it from being replaced with "ar".
The problem with your current code is that the .replace function is only taking a single variable input. This limits you from using more specific RegExp in your replace, as the matched element will not match the regex.
.replace's function option provides access to matched groups as the 1+nth variables. As a result we can leverage this to lookup our replacement strings in an array.
By utilising RegExp groups we can capture the values we're looking for and replace them as needed.
JS
var myFunction = function() {
var str = document.getElementById("text1").value;
var regexs = ['(k)','(^e|\\se)', '(e)'];
var replacers = ['g', 'B', 'ar'];
var re = new RegExp(regexs.join("|"),"gi");
// you would need to add variables to the function for each matching group you add (currently there are 3 so we have 3 groups)
str = str.toLowerCase().replace(re, function(raw, group0, group1, group2){
if(typeof group0 !== "undefined"){
return replacers[0]; // replaces with 'g'
}else if(typeof group1 !== "undefined"){
// skip over the first character (white space) and concatenate the replacement
return raw[0] + replacers[1]; // replaces with 'B'
}else if(typeof group2 !== "undefined"){
return replacers[2]; // replaces with 'ar'
}
return raw;
});
document.getElementById("demo").innerHTML = str;
};
document.getElementById('go').addEventListener('click', myFunction);
CSS
#demo{
white-space:pre;
}
NOTE: because you're outputting to an elements .innerHTML without the above CSS new lines are not displayed.
JS FIDDLE
Try The below code.
function myFunction() {
var str = document.getElementById("text1").value;
str = str.toLowerCase().split('k').join('g').split(' e').join(' B').split('\\n').join(' B').split('e').join('ar');
document.getElementById("demo").innerHTML = str;
}
Its a different approach but I got the expected output.
A simple workaround.
<script type="text/javascript">
var myfunction = function(){
var f = document.getElementById('text1').innerHTML;
var c = f.replace(/e/ig,'ar').replace(/\bar/ig,'B').replace(/k/ig,'g');
document.getElementById('text1').innerHTML = c;
}
</script>
This works.
<textarea id="source" cols="5" rows="5">
e mi e
ke fo
e di
</textarea>
<button type="button" onclick="convert()">Convert</button>
<textarea id="destination" cols="5" rows="5">
</textarea>
<script>
function replaceWord(searchFor, replaceWith, paragraph) {
if (paragraph) {
var lines = paragraph.split('\n');
for (lineNo = 0; lineNo < lines.length; lineNo++) {
var words = lines[lineNo].split(' ');
for (wordNo = 0; wordNo < words.length; wordNo++) {
if (words[wordNo] === searchFor) {
words[wordNo] = replaceWith;
}
}
lines[lineNo] = words.join(' ');
}
paragraph = lines.join('\n');
}
return paragraph;
}
function replaceWords(wordMap, paragraph) {
for(var searchFor in wordMap)
{
if(wordMap.hasOwnProperty(searchFor))
{
paragraph = replaceWord(searchFor, wordMap[searchFor], paragraph);
}
}
return paragraph;
}
function convert() {
var mapObj = {
"ke":"gar",
"e": "B"
};
var source = document.getElementById("source");
var destination = document.getElementById("destination");
destination.value = replaceWords(mapObj, source.value);
}
</script>
Here is the jsFiddle.
https://jsfiddle.net/1egs7zgc/
For what it's worth, your mapObj isn't really an array it's an object.

How to make a list randomizer

I have been working on a fairly pointless website where there are multiple "random" generators. You can check it out here: randomwordgen.net16.net
As you can see there is an unfinished generator at the bottom, that's what I'm here for. I want to get it to generate a list from things you input. My idea is to add the input field's value to the array that will make the list when you hit "Add to List." Then I will have a separate button that will generate the list using that array. The only problem is that I don't know how to add the string to the array when I only know the name of the variable, not the value. If anyone could help me with any of this, that would be great!
This is the code for the whole site:
<!DocType html>
<html>
<head>
<link rel="shortcut icon" href="https://cdn2.iconfinder.com/data/icons/thesquid-ink-40-free-flat-icon-pack/64/rubber-duck-512.png" type="image/x-icon">
<title>Random Word Generator</title>
<style>
body {
background-color:pink;
}
button.10letter {
background-color: blue;
}
button.5letter {
background-color: blue;
position:relative;
top:50px;
}
button.4letter {
background-color: blue;
position:relative;
top:100px;
}
button.3letter {
background-color: blue;
position:relative;
top:150px;
}
button.Add {
position:relative;
top:50px;
}
</style>
</head>
<body>
<h1 style="color:grey">Random word generator:</h1>
<button class="10letter" onclick="doAlert();" style="color:orange">Generate with 10 letters.</button>
<script>
function createRandomWord(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert() {
alert( "Your word is: "+createRandomWord(10)+" (bonus points if your word is real)." );
}
</script>
<button class="5letter" onclick="doAlert5();" style="color:orange">Generate with 5 letters.</button>
<script>
function createRandomWord5(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert5() {
alert( "Your word is: "+createRandomWord(5)+" (bonus points if your word is real)." );
}
</script>
<button class="4letter" onclick="doAlert4();" style="color:orange">Generate with 4 letters.</button>
<script>
function createRandomWord4(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz♀☺☻ƒ=ù"?',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert4() {
alert( "Your word is: "+createRandomWord(4)+" (bonus points if your word is real)." );
}
</script>
<button class="3letter" onclick="doAlert3();" style="color:orange">Generate with 3 letters.</button>
<script>
function createRandomWord3(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert3() {
alert( "Your word is: "+createRandomWord(3)+" (bonus points if your word is real)." );
}
</script>
<h1 style="color:grey">Name Generator:</h1>
<button style="color:orange" onclick="generator();">Generate</button>
<script>
function generator(){
var first = ["Kick","Stupid","Random Name","Officer","School-Related","Unoriginal","Original","Mousey","Website to name things?","n00b","Error","var first=name.first","Bob","Joe","Boris","Duck","Cheese","Pablo","Stimuli","Last Test Grade","First Word","Puss","Cat","Cherokee", "Jerry", "[Insert Weird First Name Here]"]
var last = ["Me","Idiot","dummy.dummy","randomwordgen.net16.net (shameless advertising)","he went that way","it was him!","DESTRUCTION...","Rats","You need advice for a name, use a website or something! Oh wait.","Opposition","Apple","404 not found","var last=name.last","You sure you want to pick this name?","McGuire","Rox","Knox","Bobert","Green","Raul","Damend","Milk","Positive","Negative","Rocky","Boots","Cherry","Parakeet","[Insert Weird Last Name Here]"]
var randomNumber1 = parseInt(Math.random() * first.length);
var randomNumber2 = parseInt(Math.random() * last.length);
var name = first[randomNumber1] + " " + last[randomNumber2];
alert(name);
}
</script>
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
var arr = [];
arr.push(Word);
}
</script>
</div>
</body>
</html>
And this is the code for the list part:
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
var arr = [];
arr.push(Word);
}
</script>
</div>
Thanks in advance!
Here is an example in which we take the input value, add it to an array, shuffle the array and then put it in a list <ul>. Every added value is added to the array and re-shuffles the list.
Try this:
EDIT
I added the shuffle function for when you just want to shuffle without adding new values.
var randomList = [];
function appendToArray() {
var word = document.getElementById("Words").value;
randomList.push(word);
updateList(randomList);
document.getElementById("Words").value = "";
}
function updateList(wordsArr) {
shuffleArr(wordsArr);
var list = document.getElementById('list');
list.innerHTML = "";
for (var i =0; i < wordsArr.length; i++) {
var word = wordsArr[i];
var li = document.createElement('li');
li.innerText = word;
list.appendChild(li);
}
}
function shuffleArr(arr) {
var j,
x,
i;
for (var i = arr.length; i; i--) {
j = Math.floor(Math.random() * i);
x = arr[i - 1];
arr[i - 1] = arr[j];
arr[j] = x;
}
}
function shuffleList() {
var list = randomList;
updateList(list);
}
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<button id="Shuffle" onClick="shuffleList()">Shuffle List</button>
<h3>List</h3>
<ul id="list"></ul>
You will need to make your array variable global so you can access it from multiple functions:
// declare this only once
var arr = [];
function appendToArray() {
var word = document.getElementById("Words").value;
// check to make sure something was entered
if (word && word.length) {
arr.push(word);
// clear the input box if added to the array
document.getElementById("Words").value = '';
}
}
Then you can have another function that picks whatever you need out of the array, which is now accessible because we moved it to the global scope of your document. You could have another button to empty the array then as well.
Is this what are you looking for?
var arr = [];
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
arr.push(Word);
}
function showArray() {
console.log(arr);
}
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<button id="Add" onClick="showArray()">Show List</button>
</div>
Initialize array outside the function. Otherwise you are making it empty every time you call the function.
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
var arr = [];
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
arr.push(Word);
}
</script>
</div>

Unable to slice strings retrieved from div's

I'm having trouble slicing text I retrieved from a div with javascript/jquery. I thought you could slice every string and that the .text() function always returned a string so I fail to see the problem. Any help will be greatly appreciated!
Fiddle
Html:
<body>
<div class="vaknaam">Div 1 :<span class="totaal">55%</span>
</div>
<div class="vaknaam">Div 2 :<span class="totaal">60%</span>
</div>
<div class="vaknaam">Div 3 :<span class="totaal">64%</span>
</div>
<div class="vaknaam">Div 4 :<span class="totaal">76%</span>
</div>
<div class="vaknaam">Div 5 :<span class="totaal">63%</span>
</div>
</body>
Javascript:
$(function () {
var divs = {};
var tempString, vakken = {};
$('.vaknaam').each(function (key, value) {
tempString = $(value).contents().filter(function () {
return this.nodeType == 3;
}).text();
tempString = tempString.slice(0, - 2);
vakken[tempString] = $(value).children('span').text();
});
for (var property in vakken) {
$('body').append("<p>" + property + "</p>");
}
});
You have several errors.
You need to declare an initialise the var vakken.
The slice method does not modify the string so you should assign what returns to something.
property var is just an index so you need to ask for vakken[property]
Your code should look like this:
$(function () {
var divs = {};
var tempString, vakken = {}; //1
$('.vaknaam').each(function (key, value) {
tempString = $(value).contents().filter(function () {
return this.nodeType == 3;
}).text();
tempString = tempString.slice(0, -4); //2
vakken[tempString] = $(value).children('span').text();
});
for (var property in vakken) {
$('body').append("<p>" + property + "</p>"); //3
}
});
Check out this codepen.
slice doesn't modify the initial string, which is immutable. Try:
tempString = tempString.slice(0, - 2);

Categories

Resources