Replacing punctuations and double quotations - javascript

Please have a look at the following code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
//Function to Trim
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g,"");
};
//Function to remove punctuation
function replaceAll(find, replace, str) {
return str.replace(new RegExp(find, 'g'), replace);
}
function count()
{
var listOfWords, paragraph, listOfWordsArray, paragraphArray;
var wordCounter=0;
listOfWords = document.getElementById("wordsList").value.trim();
listOfWords = listOfWords.toUpperCase();
//Split the words
listOfWordsArray = listOfWords.split(/\r?\n/);
//Get the paragrah text
paragraph = document.getElementById("paragraph").value.trim();;
paragraph = paragraph.toUpperCase();
//Filter all the punctuations
replaceAll("\"","",paragraph);
replaceAll("[","",paragraph);
replaceAll("]","",paragraph);
replaceAll("{","",paragraph);
replaceAll("}","",paragraph);
replaceAll("(","",paragraph);
replaceAll(")","",paragraph);
replaceAll("<","",paragraph);
replaceAll(">","",paragraph);
replaceAll(":","",paragraph);
replaceAll(",","",paragraph);
replaceAll("-","",paragraph);
replaceAll("...","",paragraph);
replaceAll("!","",paragraph);
replaceAll("<<","",paragraph);
replaceAll(">>","",paragraph);
replaceAll("","",paragraph);
replaceAll(".","",paragraph);
replaceAll("?","",paragraph);
replaceAll("/","",paragraph);
replaceAll("\\","",paragraph);
paragraphArray = paragraph.split(" ");
//check whether paragraph contains words in list
for(var i=0; i<paragraphArray.length; i++)
{
//re = new RegExp("\\b"+paragraphArray[i]+"\\b","i");
if (listOfWordsArray.indexOf(paragraphArray[i]) >= 0)
{
}
else
{
wordCounter++;
}
}
var average =0;
average = (wordCounter/paragraphArray.length)*100;
average = 100-average;
average = Math.round(average*100)/100;
window.alert("Number of Words: "+paragraphArray.length+ "\n"+ "Number of Unmatched words: "+wordCounter+ "\n"+ "Percentage "+average+"%" );
}
</script>
</head>
<body>
<center>
<p> Enter your Word List here </p>
<br />
<textarea id="wordsList" cols="100" rows="10"></textarea>
<br />
<p>Enter your paragraph here</p>
<textarea id="paragraph" cols="100" rows="15"></textarea>
<br />
<br />
<button id="btn1" onclick="count()">Calculate Percentage</button>
</center>
</body>
</html>
In here, I am trying to remove all the punctuation from the text. But my code gives no output. My knowledge lacks when it comes to web scripting languages, so I can't find the solution. How can I remove the punctuation from the text? What am I doing wrong here?
Update
According to Rahul's answer, I edited my code in the following way, but unfortunately still I have no good. I want to remove all the punctuation from the entire text, not just remove the first punctuation.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
//Function to Trim
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g,"");
};
//Function to remove punctuation
function replaceAll(find, replace, str) {
return str.replace(new RegExp(find, 'g'), replace);
}
function count()
{
var listOfWords, paragraph, listOfWordsArray, paragraphArray;
var wordCounter=0;
listOfWords = document.getElementById("wordsList").value.trim();
listOfWords = listOfWords.toUpperCase();
//Split the words
listOfWordsArray = listOfWords.split(/\r?\n/);
//Get the paragrah text
paragraph = document.getElementById("paragraph").value.trim();;
paragraph = paragraph.toUpperCase();
//Filter all the punctuations
var newstring= paragraph.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"");
var finalString = newstring.replace(/\s{2,}/g," ");
paragraphArray = finalString.split(" ");
//check whether paragraph contains words in list
for(var i=0; i<paragraphArray.length; i++)
{
//re = new RegExp("\\b"+paragraphArray[i]+"\\b","i");
if (listOfWordsArray.indexOf(paragraphArray[i]) >= 0)
{
}
else
{
wordCounter++;
}
}
var average =0;
average = (wordCounter/paragraphArray.length)*100;
average = 100-average;
average = Math.round(average*100)/100;
window.alert("Number of Words: "+paragraphArray.length+ "\n"+ "Number of Unmatched words: "+wordCounter+ "\n"+ "Percentage "+average+"%" );
}
</script>
</head>
<body>
<center>
<p> Enter your Word List here </p>
<br />
<textarea id="wordsList" cols="100" rows="10"></textarea>
<br />
<p>Enter your paragraph here</p>
<textarea id="paragraph" cols="100" rows="15"></textarea>
<br />
<br />
<button id="btn1" onclick="count()">Calculate Percentage</button>
</center>
</body>
</html>

May be you can try like this:-
var s = "Your%^%*^%^&*^% string '"+"'which*^&^&( consists of punctuation";
var st = s.replace(/["']/g, "")
var newstring= st.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`"~()]/g,"");
var finalString = newstring.replace(/\s{2,}/g," ");
alert(finalString);
The above code will replace all the punctuation from your string s
The above code works fine. Please check the JSFIDDLE.

Related

JavaScript function doesn't change the textarea in Chrome&Firefox but works in IE

I've a web page which include a JavaScript function to convert the multiple lines to a comma separated data. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add case</title>
<script type="text/javascript">
function replaceSeperator() {
var incident_box = document.getElementById("TextBoxIncidentID")
var content = incident_box.value;
//incident_box.innerHTML = content.replace(/\n/g, ",");
var ctt = content.replace(/\n/g, ",");
var lastchar = ctt.substr(ctt.length - 1);
if (lastchar != ",") {
incident_box.innerHTML = ctt;
} else {
incident_box.innerHTML = ctt.substr(0,ctt.length - 1);
}
}
</script>
</head>
<body>
<textarea name="TextBoxIncidentID" rows="2" cols="20" id="TextBoxIncidentID" textwrapping="Wrap" acceptreturn="true" onmouseout="replaceSeperator()" style="font-family:Calibri;font-size:Medium;height:60px;width:430px;margin-top: 5px;"></textarea>
</body>
</html>
It works fine in IE:
The line break replaced to comma
But it doesn't working as expected in Chrome and Firefox:
Line break replaced to comma at Dev Tool but it doesn't present on Chrome
Does any one know how to fix it?
Thanks
Use value property. innerHTML is for another purposes. Even textarea has the closing tag, the inner content is the textarea value:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add case</title>
<script type="text/javascript">
function replaceSeperator() {
var incident_box = document.getElementById("TextBoxIncidentID")
var content = incident_box.value;
//incident_box.innerHTML = content.replace(/\n/g, ",");
var ctt = content.replace(/\n/g, ",");
var lastchar = ctt.substr(ctt.length - 1);
if (lastchar != ",") {
incident_box.value = ctt;
} else {
incident_box.value = ctt.substr(0,ctt.length - 1);
}
}
</script>
</head>
<body>
<textarea name="TextBoxIncidentID" rows="2" cols="20" id="TextBoxIncidentID" textwrapping="Wrap" acceptreturn="true" onmouseout="replaceSeperator()" style="font-family:Calibri;font-size:Medium;height:60px;width:430px;margin-top: 5px;"></textarea>
</body>
</html>
You are missing a ; at the end of
var incident_box = document.getElementById("TextBoxIncidentID")
Some browsers are more forgiving to this than others.

Regex to replace "t" with "T" only if succeeded by "a","o","u" with javascript

In Javascript I want to replace "t" with "T" but only if the character after the "t" is succeeded by "a","o","u". Eg: String: tatotu, Target String: TaToTu
I couldn't find the Regex.
$(document).ready(function(){
$("#ta_1").keyup(function(event) {
var text = $(this).val();
text = text.replace("t, (\\a|\\o|\\u)","T");
$("#ta_1").val(text);
});
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<textarea id="ta_1" rows="5" cols="28" ></textarea>
</body>
</html>
Use an actual regular expression with lookaheads.
$(document).ready(function() {
$("#ta_1").keyup(function(event) {
var text = $(this).val();
text = text.replace(/t(?=a|o|u)/g, "T");
$("#ta_1").val(text);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<textarea id="ta_1" rows="5" cols="28"></textarea>
</body>
</html>
Simple solution using replace callback:
...
text = text.replace(/(t)(a|o|u)/gi, function(m, p1, p2) {
return p1.toUpperCase() + p2;
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
A simple regex like this would be suffice.
Regex: t(a|o|u)
Replace with: T$1 or T\1
Regex101 Demo
Try this
var map={"ta":"Ta", "to": "To", "tu": "Tu"};
var regex = new RegExp(Object.keys(map).join("|"), "g");
var output = "tatotu".replace(regex, function(matched){return map[matched]});
alert(output);
var str = "tatatou";
var result = str.replace(/t([aou])/g, "T$1");

Bold text in body using javascript

This code is attempting to highlight (by adding 'bold' tag) some characters that are in the HTML body. (These are specified in the JS function)
But instead of the text becoming bold, I get the 'bold' tag as the result in the html page that is getting rendered.
While I want some thing like
This is a test message
I get
This is a test <b>message</>
Any help would be awesome.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; child<len; child++){
if (children[child].nodeType === 3){ // textnode
var highLight = new Array('abcd', 'edge', 'rss feeds');
var contents = children[child].nodeValue;
var output = contents;
for(var i =0;i<highLight.length;i++){
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
The problem is that you are putting HTML in to a text node, so it is being evaluated strictly as text. One easy fix would be to simply operate on the innerHTML of the body element, like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var highLight = ['abcd', 'edge', 'rss feeds'],
contents = document.body.innerHTML;
for( i = 0; i < highLight.length; i++ ){
contents = delimiter(contents, highLight[i]);
}
document.body.innerHTML = contents;
}
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
A textNode cannot have child elements so it needs to be replaced, one way;
Replace
children[child].nodeValue = output;
With
var n = document.createElement("span");
n.innerHTML = output;
children[child].parentNode.replaceChild(n, children[child]);

Remove text from multiple textareas only on first click

I have this code which removes the text from textarea only on first click. It works ok only until I wrote the second textarea tag which is:
<textarea id="textarea2" onfocus="checkOnFocus(this);" onblur="resetInitialText(this);">Your second message</textarea>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var flag = false;
function setInitialText() {
var textarea = document.getElementById('textarea');
if (textarea.value == "") {
textarea.value = text;
}
}
function checkOnFocus(textarea) {
if (!flag) textarea.value = "";
flag = true;
}
function resetInitialText(textarea) {
if (textarea.value == "") {
textarea.value = text;
flag = false;
}
}
</script>
</head>
<body onload="setInitialText();">
<textarea id="textarea" onfocus="checkOnFocus(this);" onblur="resetInitialText(this);">Your first message</textarea>
<textarea id="textarea2" onfocus="checkOnFocus(this);" onblur="resetInitialText(this);">Your second message</textarea>
</body>
</html>
I finally found how to do what I asked:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'></script>
<script type='text/javascript'>//<![CDATA[
$(function() {
$("textarea").focus(function(event) {
// Erase text from inside textarea
$(this).text("");
// Disable text erase
$(this).unbind(event);
});
});
//]]>
</script>
</head>
<body>
<textarea rows="5" cols="30">Enter text here.</textarea>
<textarea rows="5" cols="30">Enter text here.</textarea>
</body>
</html>
Seeing from your answer, that you're ok with jquery, you could try the following as a very basic placeholder-solution:
$('[data-placeholder]').each(function () {
var placeholder = $(this).data('placeholder');
$(this).val(placeholder).on({
focus: function () {
$(this).val(function (_, value) {
return value === placeholder ? '' : value;
});
},
blur: function () {
$(this).val(function (_, value) {
return value === '' ? placeholder : value;
});
}
});
});
with:
<textarea data-placeholder="Your first message"></textarea>
<textarea data-placeholder="Your second message"></textarea>
http://jsbin.com/iyobiy/1/
function checkOnFocus(textarea){
if(!flag)
textarea.value="";
flag=false;
}
function resetInitialText(textarea){
if(textarea.value==""){
textarea.value='text';
flag=false;
}
two changes are here
1>checkOnFocus() method
flag=false;
2>resetInitialText() method
textarea.value='text';// make your own string to replace
You have only one (global) flag and two textareas, so by the time the second call is made, the flag has already been set to true. Consider using an array or a dictionary type structure to create a generic implementation. One option would be to use an array in the global scope:
var textareasAlreadyHit = new Array();
Then every time you:
function checkOnFocus(textarea)
Instead of checking for the flag, check if the array contains the id of the textarea. If it does, do nothing. If it does not, remove the text from the textarea and add the id of the textarea to the array.

Javascript for loop for text substitution

I try to use for loop as the substitution of list all
function init(){
new dEdit($('editBox'));
new dEdit($('editBox2'));
new dEdit($('editBox3'));
}
relaced by
function init(){
for(var i = 0; i < 1000; i++){
new dEdit($('editBox'+i));
}
}
but it seems it doesn't work for me. How to correct it?
Below is fully working code without "for loop":
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> New Document </title>
<meta name="title" content="" />
<meta name="author" content="0xs.cn" />
<meta name="subject" content="" />
<meta name="language" content="zh-cn" />
<meta name="keywords" content="" />
<style type="text/css" >
/* default css rule */
body { font: 12px "Verdana"; }
</style>
<script type="text/javascript" >
// shortcut
function $(s){
return typeof s == 'object'?s:document.getElementById(s);
}
var dEdit = function(el){
var me = this;
this.save = function (txt){
el.innerHTML = txt;
};
this.edit = function (e){
var e = e || event;
var target = e.target || e.srcElement;
if(target.tagName.toLowerCase() == 'input'){
return;
}
var ipt = document.createElement('input');
ipt.value = target.innerHTML;
ipt.onkeydown = function(){
if((arguments[0]||event).keyCode==13){
me.save(this.value);
}
};
ipt.onblur = function(){
me.save(this.value);
};
target.innerHTML = '';
target.appendChild(ipt);
ipt.focus();
};
el.onclick = this.edit;
};
function init(){
new dEdit($('editBox'));
new dEdit($('editBox2'));
new dEdit($('editBox3'));
}
window.onload = init;
</script>
</head>
<body>
<span id="editBox">This is sample text.</span> <br/><br/>
<span id="editBox2">This is sample text 222.</span> <br/><br/>
<span id="editBox3">This is sample text 333.</span>
</body>
</html>
Change the ids on your span tags to "editBox0", "editBox1" and "editBox2". Also, you posted this exact same question not 20-30 minutes ago and someone gave you the correct answer then too.
You need to add # prefix for ID selectors. Change your code to:
function init(){
for(var i = 0; i < 1000; i++){
new dEdit($('#editBox'+i));
}
}
Among other issues like what happens when you call dEdit(...) on an empty jQuery object...
You need a # prefix to select an ID:
$('#editBox2')
Your loop goes from 0 to 1000 and editBoxN is not a valid ID selector, so you end with
new dEdit($('editBox0'));
new dEdit($('editBox1'));
new dEdit($('editBox2'));
...
change first editBox ID, the loop variable and add a hash to the jquery selector to match the IDs
function init(){
for(var i = 1; i < 1000; i++){
new dEdit($('#editBox'+i));
}
}
The problem is the init is throwing an expection on the first value, since 'editBox0' does not exist. To fix this you can wrap each loop iteration in a try/catch.
e.g.
function init(){
for(var i = 0; i < 1000; i++){
try {
new dEdit($('editBox'+i));
} catch (e) {}
}
}
This way, if an id is undefined, the script still runs. Also, you should change <span id="editBox"> for <span id="editBox0"> or <span id="editBox1"> if you intend to have it assigned on the loop.

Categories