Unescaping RegEx Characters in JavaScript - javascript

I'm trying to make a programming language that takes the input code, which uses String.replace to slowly translate bits of the new language into JavaScript, adding regex escapes. However, when I finally print out what I have at the end, it keeps the escapes, and will totally mess up the translated code. Here is what I have now:
<!DOCTYPE html>
<html>
<head>
<title>Translating</title>
</head>
<body>
<script type="text/javascript">
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
var infile = "{{ }}";
infile = escapeRegExp(infile);
infile = infile.replace("[", "{");
infile = infile.replace("]", "}");
document.write(infile);
</script>
</body>
</html>
The escapeRegExp is the function I'm using to escape the code in the first place. The infile variable will probably be filled by PHP when I am finished, but for now it just has test code.

I thought of a very simple way to fix this: just use infile = infile.replace(/\\/g, ""); and it will replace all backslashes with null strings.

Related

Enforcing Line Breaks \n In Objective C

In Objective C I'm using the loadHTMLString to load a HTML string that has been inserted with a variable for JS. However, the string \n is not being included in the script.
For example, the code to be included:
'Product:A\nProduct:B\nProduct:C'
into java script as:
var source = 'Product:A\nProduct:B\nProduct:C'
However, in the completed HTML file the created script appears as:
var source = 'Product:A Product:B Product:C '
I need it to appear exactly as written for it to work. There are no substitutions:
var source ='Product:A\nProduct:B\nProduct:C'
Originally, I felt the problem was with formatting using: NSString stringWithFormat, but went with stringByAppendingString, but no luck - yet.
Thanks for your help
This is how the code appears when inserted by Obj C:
</head>
<body>
<h1>Absence Of Blood</h1>
<canvas id="target-canvas"></canvas>
<script>
var canvas = document.getElementById('target-canvas')
var source = 'Product:A
Product:B
Product:C
'
nomnoml.draw(canvas, source)
</script>
</body>
Obviously, it can only appear like this if code is entered in manually:
</head>
<body>
<h1>Absence Of Blood</h1>
<canvas id="target-canvas"></canvas>
<script>
var canvas = document.getElementById('target-canvas')
var source = 'Product:A\nProduct:B\nProduct:C'
nomnoml.draw(canvas, source)
</script>
</body>
I think Objective C is formatting the \n into linefeed.
A simply fix could be replace \n with ^ in a var and use javascript function to read the code and replace the ^ with \n in var and feed it to: nomnoml.draw(canvas, modifiedSource)
Or find a way to STOP Obj-C from converting \n into linefeeds.
A list of NSString options are here:
NSStrings
but I didn't see anything that would make a difference.
It seems like you want the literal text \ and n to appear in the output. To do this you need to escape the \n in your Objective-C strings.
So instead of something like this:
NSString *output = #"var source = 'Product:A\nProduct:B\nProduct:C'";
you need to escape the backslashes:
NSString *output = #"var source = 'Product:A\\nProduct:B\\nProduct:C'";
This will put a literal backslash followed by the letter "n" in the result instead of interpreting the \n special escape sequence as a newline character.

Javascript replace text within <title> with <span>title</span>

Hi i want to replace my javascript string solution like this.
input:- this is <title> and <heading>
output:- this is <span>title</span> and <span>heading</span>
can anyone help me on this.
Thanks in advance.
use regex to replace
input.replace(/</g, '<span_').replace(/>/g,'</span>').replace(/_/g,'>');
Try something like this:
var input = "this is <title> and <heading>";
var output = input.replace(/<([^>]+)>/g, "<span>$1</span>");
console.log(output);
That is, match an opening <, followed by one or more non-> characters captured as a submatch so that you can reference it as $1 in the replacement string, followed by a closing >.
Another alternative
var output = input.split("<").join("#").split(">").join("</span>").split("#").join("<span>");
console.log(output);
Use
input.replace(/<[a-zA-Z]*>/g, '<span>$&</span>');
Explanation:
.replace encloses all tags in ''. '$& is replaced with the tag. See this for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
Example:
var ta = document.getElementById('ta'), output = document.getElementById('output');
ta.value = 'I have <title> and <head> (this is just example text, you can replace).';
function replaceIt() {
output.innerText = ta.value.replace(/<[a-zA-Z]*>/g, '<span>$&</span>');
// Okay, technically Node#innerText is non-standard, so use an HTML escape function on production sites.
// For demo purposes, I just chose innerText for ease of use
}
<textarea id="ta"></textarea>
<button onclick="replaceIt()">Enclose tags in &ltspan&gt s.</button>
<div>Output:</div>
<div id="output"></div>

Javascript regex not containing keyword with backslashes

I'm having a problem with a javascript regex that has to comment out all tags inside a script tag. But it can not comment out special first script tag with id "ignorescript".
Here is a sample string to regex:
<script id="ignorescript">
var test = '<script>test<\/script>;
var xxxx = 'x';
</script>
Script tag inside ignorescipt has extra backslash because it is JSON encoded (from PHP).
And here is the final result i have to get:
<script id="ignorescript">
var test = '<!ignore-- <script>test<\/script> ignore-->;
var xxxx = 'x';
</script>
Following example works:
content = content.replace(/(<script>.*<\\\/script>)/g,
"<!--ignore $1 ignore-->");
But I need to check that it does not contain a keyword "ignorescript". If that keyword comes up then I do not want to replace anything. Otherwise add ignore comments to whole script tag So far I have gotten this far:
content = content.replace(/(<script.((?!ignorescript).)*<\/script>)/g,
"<!--ignore $1 ignore-->");
It kinda works, but not the way it supposed to be. I also have one more backslash in ending tag. So I changed it to:
content = content.replace(/(<script.((?!ignorescript).)*<\\\/script>)/g,
"<!--ignore $1 ignore-->");
Not it does not find anything at all.
Got it finally working.
Here is the working regex:
/(<script(?!\sid="ignorescript").*?<\\\/script>)/g

javascript to replace a text within [] with hyperlink

Am in a process of writing a javascript to replace a text within [] to a html link. But am stuck at generating a regular expression to match any string that is in [] and then replace it with a hyperlink.
Below is my code snippet that i have tried:
<html>
<head>
</head>
<body id="body">
Hello World [1234]<br>
[322]<br>
Hello
</body>
</html>
<script type="text/javascript">
var bodyText=document.getElementById('body').innerHTML;
var pattern = "\[(.*?)\]";
var replaceText = "Pradeep";
document.getElementById('body').innerHTML = bodyText.replace(pattern/gi, replaceText);
</script>
Can anyone please suggest me a best way to do it
Thanks,
If you have a string representing a regexp, you have to call new RegExp(str) to build a regexp from it, but you can just make a regexp literal here. Also, the i flag is not necessary since nothing in your regexp refers to letters. And, you don't use the capturing groups so you can eliminate them as well. Lastly, you need to escape the quotes in the string because the interpreter now thinks your strings ends after href=:
var bodyText = document.getElementById('body').innerHTML;
var pattern = /\[.*?\]/g;
var replaceText = "Pradeep";
document.getElementById('body').innerHTML = bodyText.replace(pattern, replaceText);
I tried \[[^\]]+\] as regexp and got the right output:
var s = 'Hello World [1234]<br>[322]<br>';
s = s.replace(/\[[^\]]+\]/ig, 'Pradeep');
// output
// Hello World Pradeep<br>Pradeep<br>

how to replace \ with \\ using javascript string functions

I have the following filepath
var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
how can I replace \ with \ so so that it prints
var imagepath="C:\\Documents and Settings\\Mahesh\\Desktop\\images\\advts.png"
You need to use the replace() method whilst escaping the \ character on each occurrence:
imagepath = imagepath.replace(/\\/g, "\\\\");
//-> "C:\\Documents and Settings\\Mahesh\\Desktop\\images\\advts.png"
If imagepath is defined with single backslash characters, those will be evaluated into an escape sequence along with the character(s) following them. At this point it's too late to replace the backslashes as they are removed from the resulting string.
It's a string literal.. By the time it's assigned to imagepath, the escape sequences are already parsed and processed, and the backslashes no longer exist in the string. You just have to have them in the string in the first place.
To demonstrate what I mean:
>>> var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
>>> imagepath
"C:Documents and SettingsMaheshDesktopimagesadvts.png"
There's no way to fix the issue at that stage.
You can use the string replace() method. Replace on W3Schools.com.
Example:
var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
document.write(imagepath.replace("\\", "\\\\"));
Upate As reko_t said, once a path is assigned to imagepath, it's a processed literal. The \ characters disappears. I've just tested my code with this example and there's no way to fix it unfortunately.
<html>
<head>
<script type="text/javascript">
function init() {
var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
alert(imagepath.replace(/\\/g, "\\\\"));
}
</script>
</head>
<body onload="init()">
</body>
</html>
The only way to do it, is to replace \ to \\ on server side, and assign it to imagepath before it gets rendered to javascript that needs to be used by javascript.
Just add after var imagepath initialisation
var imagepath=imagepath.replace("\", "\\");
return imagepath;
Try this :
str.replace(new RegExp('/', 'g'),'-')

Categories

Resources