javascript regex for escaping comma and double quote - javascript

I have to escape two special characters " and , in the string with the following rules.
Example:-
Mercu"ry should be converted into "Mercu""ry"
Mercu,ry should be converted into "Mercu,ry"
Mer"cu,ry should be converted into "Mer""cu,ry"
Rules:-
Meaning comma or double quote should be escaped with double quote.
Comma will escaped by wrapping the whole word in double quotes.
If Double quote is found, then it double quote should be added at its
position. Also the whole word should be wrapped inside the double
quotes.
Please suggest the regex pattern in javascript.

var test = [
'Mercu"ry', 'Mercu,ry', 'Mer"cu,ry', 'Mercury'
];
for (x in test) {
var s = test[x];
if (s.indexOf('"') != -1) {
s = s.replace(/"/g, '""');
}
if (s.match(/"|,/)) {
s = '"' + s + '"';
}
alert(s);
}
Test: http://jsfiddle.net/ZGFV5/
Try to run the code with Mer""cury :)

Just always wrap the word in double quotes, and replace all double quotes with two:
function escapeWord(word) {
return '"' + word.replace(/"/g, '""') + '"';
}

The regular expression to achieve this is /"/g, so the following will work for your examples:
var test1 = 'Mercu"ry'
var test2 = 'Mercu,ry'
var test3 = 'Mer"cu,ry'
var regex = /"/g;
var example1 = '"' + test1.replace(regex, '""') + '"';
var example2 = '"' + test2.replace(regex, '""') + '"';
var example3 = '"' + test3.replace(regex, '""') + '"';
alert(example1 + " : " + example2 + " : " + example3);
Example fiddle

Related

Check if String Contains Letters with If and Else Statements

I have a string named uppercase and if it contains letters, nothing happens. Although, if it doesn't then it evaluates uppercase. Here's my if and else statement:
if(uppercase.substring(0,9) == "CALCULATE")
{
if(uppercase.substring(10,uppercase.length.contains("[a-zA-Z]+")))
{
} else{
var ans = eval(uppercase.substring(9,uppercase.length));
sendSpecialChat = [true, ans];
}
}
Although, it doesn't work. What's wrong with my code?
Likely your issue is here:
uppercase.substring(10,uppercase.length.contains("[a-zA-Z]+")
If you are testing if the part of uppercase contains any letters beyond the 10th character (allowing for zero index), then you can use substring with a suitable regular expression, e.g.:
/[a-z]/i.test(uppercase.substring(10,uppercase.length))
var uppercase = "0123456789Hey"
console.log('"' + uppercase + '" : ' +
/[a-z]/i.test(uppercase.substring(10,uppercase.length)));
var uppercase = "0123456789*&^"
console.log('"' + uppercase + '" : ' +
/[a-z]/i.test(uppercase.substring(10,uppercase.length)));
Or just a regular expression:
var uppercase = "0123456789Hey";
console.log('"' + uppercase + '" : ' + /^.{10}[a-z]/i.test(uppercase));
var uppercase = "0123456789*&^";
console.log('"' + uppercase + '" : ' + /^.{10}[a-z]/i.test(uppercase));

why is my string not being a string?

Seeking some cheeky on the fly help here. Been staring at this for along time and cannot see why the whole thing is not maintaining being a string:
var str =
'<script type="cats/conversion">
{"type":"REGISTER",
"params":{"partner_conversion_id":"' + {{sku}} + '",
"f":"' + {{accountHolderName}} + '",
"e":"' + {{dl userid}} + '"}
}
<\/script>';
I had expected that all of str is a string but my text editor is telling me that it's not. Where have I typeod a ' or "?
Help!!
You can't (safely and reasonably) do multi-line string literals in JavaScript. You have to build them up using concatenation (the + operator). You can do it like this:
var str = '<script type="cats/conversion">' +
'{"type":"REGISTER",' +
'"params":{"partner_conversion_id":"' + {{sku}} + '",' +
'"f":"' + {{accountHolderName}} + '",' +
'"e":"' + {{dl userid}} + '"}' +
'}' +
'<\/script>';
Note: I have no idea what the {{sku}} and similar placeholders in your script are. I assume those are for some templating system. They are not, as written, valid syntax.
Edit: Technically, as Alex pointed out in his answer, you can do multi-line literals by escaping the newline with \. As Alex says, however, this is "considered horrible practice" and prone to breaking for all kinds of reasons. Don't do it!
Try this
var str = '<script type="cats/conversion">'+
'{"type":"REGISTER",'+
'"params":{"partner_conversion_id":"' + sku + '",'+
'"f":"' + accountHolderName + '",'+
'"e":"' + dl_userid + '"}'+
'} '+
'<\/script>';
In Javascript you have to add a \ to the end of a line to indicate a multi-line string. This is considered HORRIBLE practice, because if the \ is followed by any whitespace, it will throw a syntax error.
var ok = "this is \
my multiline string!";
var notOk = "this is \
my multiline string!";
The 2nd is an error because there is a space after the \ at the end of the line.
If you are using ES6, you can use template strings with backticks instead:
var x = `This is my
multiline string!`;
If ES6 is not an option and you don't want to follow bad practices by using \, concatenate multiple strings together or insert newlines in your string like so:
var myString = "this is line 1" +
" this is line 2" +
" this is line 3";
or
var myString = "this is line 1\n this is line 2\n this is line 3";
You either do it in one line
var str ='<script type="cats/conversion"> {"type":"REGISTER", "params":{"partner_conversion_id":"' + {{sku}} + '", "f":"' + {{accountHolderName}} + '", "e":"' + {{dl userid}} + '"}} <\/script>';
For readability if you want it to be multi lined you have to concatenate the string.
var str = '<script type="cats/conversion">' +
'{"type":"REGISTER",' +
'"params":{"partner_conversion_id":"' + {{sku}} + '",' +
'"f":"' + {{accountHolderName}} + '",' +
'"e":"' + {{dl userid}} + '"}' +
'}' +
'<\/script>';
I think you mean to do this:
var str =
'<script type="cats/conversion">
{"type":"REGISTER",
"params":{"partner_conversion_id":"' + '{{sku}}' + '",
"f":"' + '{{accountHolderName}}' + '",
"e":"' + '{{dl userid}}' + '"}
}
<\/script>';
The {{}}'s need to be wrapped in quotes.

Difficulty implementing Equals Operator

I have two Parse generated objectId strings that I know are equal, because I print them out and read them, and they are the same.
They are requestedUserId and requestingUserId.
I have tried as mentioned in the comments to check for invisible characters
console.log('"' + requestedUserId + '"')
console.log('"' + requestingUserId + '"')
However, as suspected, they print out equal.
The code below never runs, it jumps to the else statement. Is there a problem with my logic, or anything else that is readily apparent?
Parse.Cloud.beforeSave("FriendRequest", function(request, response) {
var requestedUserId = request.object.get("to")
var requestingUserId = request.object.get("from")
console.log('"' + requestedUserId + '"')
console.log('"' + requestingUserId + '"')
// One cannot request oneself
if (requestedUserId == requestingUserId) {
console.log("can't send a request to yourself")
response.error("can't send a request to yourself");
} else {
(...)
}
});
As per my comment, I suggest that you check the length of the 2 strings rather than relying on visibility in your console.
var str1 = 'abc123';
var str2 = 'abc123' + String.fromCharCode(0);
console.log('"' + str1 + '"', str1.length);
console.log('"' + str2 + '"', str2.length);
console.log(str1 == str2);

How to get all the contents between two curly braces with or without using regex

I have the following code segment:
function test(){
try {
---------------some contents-------
}
catch(e){
}
}
Now, I want the codes between the 1st pair of curly braces. The output should be like:
try {
---------------some contents-------
}
catch(e){
}
How can I do that with or without using Regex? I tried using the following regex:
Pattern p = Pattern.compile("\\{([^}]*)\\}");
Matcher m = p.matcher(s); // s contains each line of the above text
while (m.find()) {
System.out.println(m.group(1));
}
But, It only fetches contents if its there in a single line or no multiple lines of braces exist.
You could've searched better
Use substr and indexOf / lastIndexOf:
function test(){
try { /*---------------some contents-------*/ }
catch(e) {}
}
var testStr = String(test);
testStr = testStr.substr(testStr.indexOf('{') + 1);
document.querySelector('#result').textContent =
testStr.substr(0, testStr.lastIndexOf('}'));
<pre id="result"></pre>
Just Try It:
String s = "function test(){"
+ "try {"
+ "---------------some contents-------"
+ "}"
+ "catch(e){"
+ "}"
+ "}";
int bracketStartIndex = s.indexOf("{");
System.out.println("START INDEX = " + bracketStartIndex);
int bracketEndIndex = s.lastIndexOf("}");
System.out.println("END INDEX = " + bracketEndIndex);
System.out.println("OUTPUT STRING : " + s.substring(bracketStartIndex, bracketEndIndex));

Why won't replace work with my regex object when test does?

I feel silly asking this because I'm betting the answer is staring right at me but here goes.
I'm taking a string from the CSS style textDecoration and trying to remove the underline portion of the string (and any whitespace around it). It returns true when I run test() but when I do the replace method the string is unaltered. Help?
My code:
textDecoration = function(str) {
var n_str = str + '|/\s' + str + '|/\s' + str + '/\s|' + str + '/\s';
var nre = new RegExp(n_str, "g");
debug_log('Found or not: ' + nre.test(txt));
txt.replace(nre, '');
debug_log('Result: ' + txt);
debug_log('-----------------------');
}
var txt = "underline";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "underline overline line-through";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "overline underline line-through";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "overline line-through underline";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
Output:
replace() returns a new string with the replaces and don't change the actual string. You should do something like:
var newString = txt.replace(nre, '');
debug_log('Result: ' + newString);
test returns a boolean. replace returns a new string. It does not alter the string.
Also, your regular expression is quite odd. Applying str = "underline", you will get:
/underline|\/sunderline|\/sunderline\/s|underline\/s/
which does not match whitespaces, but "/s".

Categories