Click here to Skip to main content
15,892,768 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i m replacing my written words to javascript original syntax for less writing and saving time, i m getting near to it but many problems for a beginner, i have stuck here with RegExp() method where i just knew that how to find symbols like "\\(" or /\(/
but i dont understand why the code doesn't work just watch my script and answer me.

What I have tried:

HTML
<!DOCTYPE html>
<html>
<body>

<textarea type= "text" id = "in1" rows = "4">
</textarea>
<br>

<textarea type= "text" id = "in2" >
</textarea>

<script>

function replace()
{
/* this code will always show bottom line of textarea */
var ta = document.getElementById("in1");

ta.scrollTop = ta.scrollHeight;

var in2 = document.getElementById("in2").value;

/* this will replace all characters to onother characters */
var replaceChars =
{
"d.": "document.",
"b." : "body.",
"w\\(": "write(",
"wl\\(" : "writeln(",
"ce\\(" : "createElement(",
"ctn\\(" : "createTextNode(",
"ac\\(" : "appendChild("
};

var re = new RegExp(Object.keys(replaceChars).join("|"),"g");

var replaced = in2.replace(re ,function (match)
{return replaceChars[match];});

document.getElementById("in1").value = replaced;
};

/* if i type in second textarea "d.w();" it returns "document.undefined);" and i want "document.write();" how to solve this undefined problem */

</script>

</body>
</html>
Posted
Updated 21-Aug-16 18:16pm
v2

1 solution

Your problem is that the march for w\\( is w( which is not in your array. The match is different from the RegEx.

Another bug:
d. and b. are not matching "d" or "b" followed by a point, they match "d" or "b" followed by anything, a letter, a number, a space ...

Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
 
Share this answer
 
Comments
prasad sawant 22-Aug-16 1:16am    
nice recomendation but i want exact explanation code, what link u have given me its all perl programming language codes, i m not familier with it, i want javascript code, i saw on w3schools.com but there is no complex matching technics, and if i type "w(" : "write(" my page shows blank.
Patrice T 22-Aug-16 1:42am    
95% of perl RegEx is same as JS RegEx ans the difference is only on advanced features.
You need to understand that most of the time, a RegEx and what it match are 2 different things.
For example "d." with match "d." AND "d1" "da" "d(" "d," "d%" ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900