Search for Literal String - javascript

I'm trying to find certain characters in a string and I receive the error "Unterminated string literal".
I'm searching for "\". Is there a way to find this character (or other literal strings) without an error?
thanks,
Here is the simple function:
function test() {
var a = "AGA_NAA1\MTH1.33";
var rep = a.replace("\","-");
Browser.msgBox(rep);
}
ERROR: Unterminated string literal.

I realize you are sharing a simplified example. However, this is happening because on variable a you also need double backslash because backslash is a special "escape" character:
function test() {
var a = "AGA_NAA1\\MTH1.33";
var rep = a.replace("\\","-");
Browser.msgBox(rep);
}

Related

Escaping backslash in a string containing backslash

I have a string containing I\u2019m (with backslashes not escaped)
var myString = 'I\\u2019m'; // I\u2019m
But then I need a function that 'escape backslashes' that string, so the function I'm looking for would return I'm
backslashString(myString); // I'm
I've tried using eval:
function backslashString(input){
input = input.replace(/'/g, "\\'"); // Replace ' with \' that's going to mess up eval
return eval(`'${input}'`);
}
But is there a proper way of doing it? I'm looking for a function that escape backslashes a string containing I\u2019m to I'm and also handles if there's an extra backslash (A lost \ backslash)
EDIT:
I did not ask what I meant from the start. This not only applies to unicode characters, but applies to all backslash characters including \n
The backslashes aren’t the real problem here - the real problem is the difference between code and data.
\uXXXX is JavaScript syntax to write the Unicode codepoint of a character in a text literal. It gets replaced with the actual character, when the JavaScript parser interprets this code.
Now you have a variable that contains the value I\u2019m already - that is data. This does not get parsed as JavaScript, so it does mean the literal characters I\u2019m, and not I’m. eval can “fix” that, because the missing step of interpreting this as code is simply what eval does.
If you do not want to use eval (and thereby invite all the potential risks that entails, if the input data is not completely under your control), then you can parse those numeric values from the string using regular expressions, and then use String.formCharCode to create the actual Unicode character from the given code point:
var myString = 'I\\u2019m and I\\u2018m';
var myNewString = myString.replace(/\\u([0-9]+)/g, function(m, n) {
return String.fromCharCode(parseInt(n, 16)) }
);
console.log(myNewString)
/\\u([0-9]+)/g - regular expression to match this \uXXXX format (X=digits), g modifier to replace all matches instead of stopping after the first.
parseInt(n, 16) - to convert the hexadecimal value to a decimal first, because String.fromCharCode wants the latter.
decodeURIComponent(JSON.parse('"I\\u2019m"'));
OR for multiple
'I\\\u2019m'.split('\\').join().replace(/,/g,'');
'I\u2019m'.split('\\').join().replace(/,/g,'');
Looks like there's no other way other than eval (JSON.parse doesn't like new lines in strings)
NOTE: The function would return false if it has a trailing backslash
function backslashString(input){
input = input.replace(/`/g, '\\`'); // Escape quotes for input to eval
try{
return eval('`'+input+'`');
}catch(e){ // Will return false if input has errors in backslashing
return false;
}
}

RegExp using regex + variables

I know there are many questions about variables in regex. Some of them for instance:
concat variable in regexp pattern
Variables in regexp
How to properly escape characters in regexp
Matching string using variable in regular expression with $ and ^
Unfortunately none of them explains in detail how to escape my RegExp.
Let's say I want to find all files that have this string before them:
file:///storage/sdcard0/
I tried this with regex:
(?:file:\/\/\/storage\/sdcard0\(.*))(?:\"|\')
which correctly got my image1.jpg and image2.jpg in certain json file. (tried with http://regex101.com/#javascript)
For the life of me I can't get this to work inside JS. I know you should use RegExp to solve this, but I'm having issues.
var findStr = "file:///storage/sdcard0/";
var regex = "(?:"+ findStr +"(.*))(?:\"|\')";
var re = new RegExp(regex,"g");
var result = <mySearchStringVariable>.match(re);
With this I get 1 result and it's wrong (bunch of text). I reckon I should escape this as said all over the web.. I tried to escape findStr with both functions below and the result was the same. So I thought OK I need to escape some chars inside regex also.
I tried to manually escape them and the result was no matches.
I tried to escape the whole regex variable before passing it to RegExp constructor and the result was the same: no matches.
function quote(regex) {
return regex.replace(/([()[{*+.$^\\|?])/g, '\\$1');
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
What the hell am I doing wrong, please?
Is there any good documentation on how to write RegExp with variables in it?
All I needed to do was use LAZY instead of greedy with
var regex = "(?:"+ findStr +"(.*?))(?:\"|\')"; // added ? in (.*?)

Using regex to split double hyphen but not single hyphen

I have an html element id that looks like this:
dp__1-2--1-3
I'm trying to use the JavaScript split() function to lop off and return the final '1-3'
My regex skills are poor but a bit of searching around got me to this point:
var myId = "dp__1-2--1-3";
var myIdPostFix = myId.split(/[\-\-]+/).pop();
Unfortunately that returns me only the '3'.
So my question is how do I split double hyphens but NOT single hyphens?
It's the brackets in the regular expression that keeps it from working. A set will match one of any of the characers in it, so [\-\-] is the same as [\-], i.e. matching a single hyphen.
Just remove the brackets:
var myIdPostFix = myId.split(/--/).pop();
or just use the string '--' instead of a regular expression:
var myIdPostFix = myId.split('--').pop();
split accepts a regular expression or a string as the first argument.
You were very close. You can achieve what you want with:
var myIdPostFix = myId.split("--").pop();

How to use symbols as parameters for javascript functions

In my header i'm using the function
function changefinal(text)
{
if (text == ".")
{
final = final + ".";
}
}
But when I call the function as changefinal(.) my final variable does not change. Not sure what I'm doing wrong here. Am I defining the parameter wrong?
You have to quote your symbols. In JavaScript, a double quotation character has the same effect as a single quote-character. When you're quoting something in JavaScript, the contents inside the quote is interpreted literally, and the created object is a string.
changefinal(".");
changefinal('.');
If you ever have to use a literal quote inside the same quote (example" inside "..."), a prefix the inner quote by a backslash, to escape the quote:
var string = 'I\'m Rob W.';
alert(string); //shows: I'm Rob W.
var attempt = 'I'm Rob W.'; //Notice: No backslash
^ Syntax error
Well
changefinal(.);
is a syntax error. You probably want
changefinal(".");

Javascript replace several character including '/'

Im using this snippet to replace several characters in a string.
var badwords = eval("/foo|bar|baz/ig");
var text="foo the bar!";
document.write(text.replace(badwords, "***"));
But one of the characters I want to replace is '/'. I assume it's not working because it's a reserved character in regular expressions, but how can I get it done then?
Thanks!
You simply escape the "reserved" char in your RegExp:
var re = /abc\/def/;
You are probably having trouble with that because you are, for some reason, using a string as your RegExp and then evaling it...so odd.
var badwords = /foo|bar|baz/ig;
is all you need.
If you INISIST on using a string, then you have to escape your escape:
var badwords = eval( "/foo|ba\\/r|baz/ig" );
This gets a backslash through the JS interpreter to make it to the RegExp engine.
first of DON'T USE EVAL it's the most evil function ever and fully unnecessary here
var badwords = /foo|bar|baz/ig;
works just as well (or use the new RegExp("foo|bar|baz","ig"); constructor)
and when you want to have a / in the regex and a \ before the character you want to escape
var badwords = /\/foo|bar|baz/ig;
//or
var badwords = new RegExp("\\/foo|bar|baz","ig");//double escape to escape the backslash in the string like one has to do in java

Categories

Resources