Created
April 10, 2016 14:44
-
-
Save Prodge/324165c00941013c88435e15b517018c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p> | |
this is a test of this paragraph. | |
</p> | |
<label>Balance</label> | |
<input name="operation" id="do_balance" type="radio" checked/> | |
<label>Substitute</label> | |
<input name="operation" id="do_substitute" type="radio" /> | |
</br> | |
<input id="inp"/> | |
</br> | |
<button id="btn">Click</button> | |
<script> | |
function check_brackets(){ | |
var str = document.getElementById('inp').value; | |
var opening = 0; | |
var closing = 0; | |
for(var i = 0; i < str.length; i++){ | |
if(str[i] == '('){ | |
opening ++; | |
} | |
if(str[i] == ')'){ | |
closing ++; | |
} | |
// There should never be more closing than opening | |
if(closing > opening){ | |
break; | |
// After break, not balanced alert will be issued. | |
// This is because for the func to enter this scope the brackets must not be ballanced | |
} | |
} | |
if(opening == closing){ | |
alert('Balanced'); | |
}else{ | |
alert('Not Balanced'); | |
} | |
} | |
function substitute_string(){ | |
var str = document.getElementsByTagName('p')[0].innerHTML; | |
var old_str = 'this'; | |
var new_str = 'that'; | |
for(var i = 0; i < str.length - old_str.length; i++){ | |
if(str.slice(i, i + old_str.length) == old_str){ | |
str = str.slice(0, i) + new_str + str.slice(i + old_str.length, str.length); | |
} | |
} | |
document.getElementsByTagName('p')[0].innerHTML = str; | |
} | |
document.getElementById('btn').onclick = function() { | |
if(document.getElementById('do_balance').checked){ | |
check_brackets(); | |
}else{ | |
substitute_string(); | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment