How to escape sanitize strings like "\\r\\n " - javascript

I am recieving strings like:
"\\r\\n "
"\\r \\n"
"\\n \\r "
etc from a third party API.
I need to convert these to empty string before storing them into DB. How can I properly sanitize these in Node.js?
I can use .replace but I want to make sure to catch all edge cases.

Considering you just want to replace the string with no values other than space character class or escaped space characters.
let str = `"\\r\\n "
"\\r \\n"
"\\n \\r "
"\\n \\r Hello"
`
let op = str.replace(/^"(?:\\r|\\n|\s)*"?$/gm,'')
console.log(op)

Try this :
console.log("\\n \\r ".replace(/\\(n|r)\s*/g,""));

Try ( i use \\\\r for slashesh as escape characters in JS to poperly generate your input string - which is shown console)
let input=" \\\\r \\\\n ";
let output= input.replace(/\s*(\\\\r|\\\\n)\s*/g, '');
console.log(`input : "${input}"` );
console.log(`output : "${output}"`);

Related

How to replace inner double quotes to single quote using regex

I've got something like this data that comes from API and I need to do JSON.parse this, but the problem was there were inner double quotes so I can't parse it what should I do, can I use regex or something.
const dataString = '{"EN" : "2. This English "Blha Blha" "Woo Woo" something wrong."}';
I also used this regex
replace(/(^"|"$)|"/g, "'");
but by using this regex it's replace all the double quotes with single quotes like this =>
{'EN' : '2. This English 'Blha Blha' 'Woo Woo' something wrong.'};
I only want to replace the quotes like this
{'EN' : '2. This English "Blha Blha" "Woo Woo" something wrong.'};
The thing is that single quotes are not valid symbols for JSON if they are used to wrap key/values. To make it clear - you need to escape double-quote symbols in values. A better approach is to update your API with that correction. More ugly but working way is placed below:
const dataString = '{"EN" : "2. This English "Blha Blha" "Woo Woo" something wrong."}';
const normalize = (dataString) => {
let newString = dataString;
newString = newString.replaceAll(`"`, `\\\"`);
newString = newString.replaceAll(`{\\\"`, `{"`);
newString = newString.replaceAll(`\\\"}`, `"}`);
newString = newString.replaceAll(`\\\" : \\\"`, `" : "`);
return newString;
};
console.log(JSON.parse(normalize(dataString)));

Split a string of strings by 2 delimeters

My string looks like
"<!number|Foo bar> <!number|Foo bar> <!number|foo bar>"
I have like to split the string by "<" and ">" so that the new array becomes
["<!number|string>", "<!number|string>" ].
I tried str.split('> <'), which gives me
["<!numer|string", "!number|string>"].
Also I tried using regex to str.split(/\<> /)
which gives me ["<!number|string> <!number|string>"].
How to split it correctly?
At work so I can't fix the nitty gritty with the regex, but the below works given the string
const str = `<!1|Foo bar> <!2|Bar Baz> <!3| xxx yyy>`;
console.log(str.split(/(<[\s\S]*?>)/gm).filter((n)=> { return (n!="" && n!=" ") }));
Just split on space:
let str = "<!number|string> <!number|string> <!number|string>";
console.log(str.split(" "));

Remove commas from a string using js

I have a Address like
Address : 273A-84, Sundharam Street,, Ganthi Path, Kovai,,,,India,641001
If string has more than 2 commas i want to replace with single comma.
In above address next to street and next to kovai there is multiple commas.I want to replace with single comma.
My expected output is:
Address : 273A-84, Sundharam Street,Ganthi Path,Kovai,India,641001
Please suggest regular expression.
var str = "Address : **273A-84, Sundharam Street,, Ganthi Path, Kovai,,,,India,641001**";
str.replace(/\,{1,}/gi, ',');
DEMO:http://jsbin.com/sejuma/2/
You can try this:-
var str="Address : 273A-84, Sundharam Street,, Ganthi Path, Kovai,,,,India,641001 ";
res = str.replace(/^[, ]+|[, ]+$|[, ]+/g, ",").trim();
alert("{" + res+ "}");

Javascript/Regex: Expression works in one environment and not another

I am trying to only allow alphanumeric entry or these characters:'()-_. (with the "." included)
Using regexpal.com I entered this regular expression: [^a-zA-Z0-9()\.'\-\_ ]
It is correctly identifying * and # as a match. What's baffling is that I have that same exact expression in my javascript on an .aspx page and it is not catching * or #. I have confirmed that is indeed entering that function and that the expression evaluates. Here is that code:
$(".validateText").keyup(function (e) {
var matchPattern = "[^a-zA-Z0-9()\.'\-\_ ]";
var regEx = new RegExp(matchPattern);
console.log("Regex: " + regEx + "\nValue of " + e.target.id + " is: " + e.target.value);
if (regEx.test(e.target.value)) {
console.log("Found invalid data.");//I don't get here with # or *
var failingChar = e.target.value.length - 1;
e.target.value = e.target.value.substring(0, failingChar);
}
});
Rather than using string literals to define regexes, use regex literals.
var regEx = /[^a-zA-Z0-9()\.'\-\_ ]/;
String literals interpret backslashes as escape characters, so they need to be escaped. Regex literals don't require this.
As per Bergi's suggestion, you wouldn't even need to escape all those characters.
/[^a-zA-Z0-9().'_ -]/
You could probably even use the general \w character.
/[^\w().' -]/
var matchPattern = "[^a-zA-Z0-9()\\.'\\-\\_ ]";
Would work.

line break introduction in confirm message string

I have a confirmation pop-up dialog in which I am passing a variable which is a comma separated string.
How can I replace the commas and introduce a line break?
I tried using replace. I tried passing '\n' separated list from back-end. But nothing seems to work — though a normal confirm() used for testing purposes is working fine.
var listcontrol = document.getElementById(id3);
var List = listcontrol.innerText;
var finallist = List.replace("\n", "\n");
if (checkboxCell.checked == false) {
if (labelCell.innerText == "Yes") {
confirm("The selected exam is present in the following certifications: " + "\n" + finallist + "\n" +
"Uplanning this exam here would unplan the same exam under other certification(s) also.");
}
}
In your code you are replacing "\n" with "\n", which would make no difference. You want to replace "," with "\n" instead, right?
var string = "Demetrius Navarro,Tony Plana,Samuel L. Jackson";
alert(string);
alert(string.replace(/,/g, "\n"));​​​​
Live test - http://jsfiddle.net/9eZS9/
Js replace is,
string.replace(searchvalue,newvalue)
var finallist = List.replace(/,/g, "\n");
If your "pop-up dialog" is a custom html/css-based dialog then newline characters would be treated (more or less) the same as space characters. You'd need to use <br> elements instead, so:
var finallist = List.replace(/,/g, "<br>");
Note the use of the regex as the first argument for replace() - this is needed in order to do a global replace.
For use in a standard confirm you'd need newline characters like you were doing, but with a regex rather than a string for the replace() search term:
var finallist = List.replace(/,/g, "\n");

Categories