Replace null bytes - javascript

I want to replace null bystes from string. But after replacing of the null bytes \u0000 of the string
let data = {"tet":HelloWorld.\u0000\u0000\u0000\u0000"}
let test = JSON.parse(data).tet.replace("\u0000", "");
I am getting always following value:
HelloWorld.[][][][]
This are not array brackets or something like that.
I just need the value HelloWorld. How can I do this?
Ok, the solution was to replace all bytes.
.replace(new RegExp("\u0000", "g"), "");

A normal string replace only replaces the first occurence.
But by using a regex with a global flag it'll replace all occurences.
Example snippet :
console.log("bar bar".replace("bar","foo"));
console.log("bar bar".replace(/bar/g,"foo"));
let data = {"test":"HelloWorld.\u0000\u0000\u0000\u0000"};
console.log("before: " + data.test);
console.log("before (stringified): " + JSON.stringify(data.test));
// removing all the NULL unicode characters
data.test = data.test.replace(/\u0000/g,'');
console.log("after (stringified): " + JSON.stringify(data.test));

Related

The difference between "" vs " " Javascript

I used this to remove white spaces from a string.
returnString.split(" ").filter(substr => substr !== "");
In my head it should be this:
returnString.split(" ").filter(substr => substr !== " ") //note the space between the " "
why doesnt the bottom one work? Is it JS sytax?
Answer: If theres a space at the beginning of the string, its split with an empty string, (so substr !== "") removes that from the returned array when splitting the string.
returnString.replace(/\s/g,'') Would be a superior way of doing this.
"" is an empty string.
" " is a space character.
They cannot be used interchangeably.
"" is an empty string.
If there is a space at the beginning of the string, it will split that space with an empty string.
that is why substr !== "" is needed to remove the empty string.
As mentioned in the comments, you’re splitting on whitespaces, creating indices for said whitespaces in an array.
const returnString = 'Hello I am Victor'
const str = returnString.split("").filter(substr => substr !== " ");
console.log(str.join(''))
would get you the desired result.
However, a regex pattern would be best suited for this use case.
returnString.replace(/\s/g, '')

How to replace all newlines after reading a file

How can I replace a newline in a string with a ','? I have a string that is read from a file:
const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);
It takes a string from a file:
a,b,c,d,e,f
,,,,,
g,h,i,j,k,l
I'm able to detect the newline with this:
if (char === '\n')
But replacing \n like this doesn't work
str = csvString.replace('/\n/g');
I want to get the string to look like this:
a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,
You can add , at end of each line like this
$ - Matches end of line
let str = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`
let op = str.replace(/$/mg, "$&"+ ',')
console.log(op)
Try replacing the pattern $ with ,, comma:
var input = 'a,b,c,d,e,f';
input = input.replace(/$/mg, ",");
console.log(input);
Since you intend to retain the newlines/carriage returns, we can just take advantage of $ to represent the end of each line.
let text = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`;
let edited = text.replace(/\s+/g, '');
console.log( edited )
You can try this solution also. \s means white spaces.
You may try out like,
// Let us have some sentences havin linebreaks as \n.
let statements = " Programming is so cool. \n We love to code. \n We can built what we want. \n :)";
// We will console it and see that they are working fine.
console.log(statements);
// We may replace the string via various methods which are as follows,
// FIRST IS USING SPLIT AND JOIN
let statementsWithComma1 = statements.split("\n").join(",");
// RESULT
console.log("RESULT1 : ", statementsWithComma1);
// SECOND IS USING REGEX
let statementsWithComma2 = statements.replace(/\n/gi, ',');
// RESULT
console.log("RESULT2 : ", statementsWithComma2);
// THIRS IS USING FOR LOOP
let statementsWithComma3 = "";
for(let i=0; i < statements.length; i++){
if(statements[i] === "\n")
statementsWithComma3 += ','
else
statementsWithComma3 += statements[i]
}
// RESULT
console.log("RESULT3 : ", statementsWithComma3);
I believe in some systems newline is \r\n or just \r, so give /\r?\n|\r/ a shot

How should a JSON string with quotes inside can be parsed with javascript

var str = '{"Language":"en","Type":"General","Text":""Mela" means "apple" in Italian"}';
Now JSON.parse(str) throws this error
Uncaught SyntaxError: Unexpected token M in JSON at position 43
Now replacing quotes escapes whole string and parsed JSON is not usable anymore
str = str.replace(/\\([\s\S])|(")/g,"\\$1$2");
"{\"Language\":\"en\",\"Type\":\"General\",\"Text\":\"\"Mela\" means \"apple\" in Italian\"}"
Other solutions like below do not seem to be working in this scenario
How to escape a JSON string containing newline characters using JavaScript?
You need to add a backslash before each double quote within your string as:
const str = '{"Language":"en","Type":"General","Text": "\\"Mela\\" means \\"apple\\" in Italian"}';
const obj = JSON.parse(str)
console.log(obj.Text)
In JSON you don't escape double quotes of the property name or the begging of the property value, just escape what's inside property value:
{\"Text\":\"\"Mela\" means ....
It should be like this:
{"Text":"\"Mela\" means ....
This can be done with multiple replacements:
var str = '{"Language":"en","Type":"General","Text":""Mela" means "apple" in Italian"}';
str = str.replace(/"/,"'"); //Replace all " with '
str = str.replace(/{'/,'{"') //Restore " to start of JSON
str = str.replace(/','/,'","'); //Restore " around JSON , separators
str = str.replace(/':'/,'":"'); //Restore " around JSON : separators
str = str.replace(/'}/,'"}'); //Restore " to end of JSON
str = str.replace(/'/,'\"'); //All remaining ' must be inside of data, so replace with properly escaped \"
console.log(str);
EDIT: A problem with this solution is that is will also replace original ' characters with " inside the text.

How to replace found regex sub string with spaces with equal length in javascript?

In javascript if I have something like
string.replace(new RegExp(regex, "ig"), " ")
this replaces all found regexes with a single space. But how would I do it if I wanted to replace all found regexes with spaces that matched in length?
so if regex was \d+, and the string was
"123hello4567"
it changes to
" hello "
Thanks
The replacement argument (2nd) to .replace can be a function - this function is called in turn with every matching part as the first argument
knowing the length of the matching part, you can return the same number of spaces as the replacement value
In the code below I use . as a replacement value to easily illustrate the code
Note: this uses String#repeat, which is not available in IE11 (but then, neither are arrow functions) but you can always use a polyfill and a transpiler
let regex = "\\d+";
console.log("123hello4567".replace(new RegExp(regex, "ig"), m => '.'.repeat(m.length)));
Internet Exploder friendly version
var regex = "\\d+";
console.log("123hello4567".replace(new RegExp(regex, "ig"), function (m) {
return Array(m.length+1).join('.');
}));
thanks to #nnnnnn for the shorter IE friendly version
"123hello4567".replace(new RegExp(/[\d]/, "ig"), " ")
1 => " "
2 => " "
3 => " "
" hello "
"123hello4567".replace(new RegExp(/[\d]+/, "ig"), " ")
123 => " "
4567 => " "
" hello "
If you just want to replace every digit with a space, keep it simple:
var str = "123hello4567";
var res = str.replace(/\d/g,' ');
" hello "
This answers your example, but not exactly your question. What if the regex could match on different numbers of spaces depending on the string, or it isn't as simple as /d more than once? You could do something like this:
var str = "123hello456789goodbye12and456hello12345678again123";
var regex = /(\d+)/;
var match = regex.exec(str);
while (match != null) {
// Create string of spaces of same length
var replaceSpaces = match[0].replace(/./g,' ');
str = str.replace(regex, replaceSpaces);
match = regex.exec(str);
}
" hello goodbye and hello again "
Which will loop through executing the regex (instead of using /g for global).
Performance wise this could likely be sped up by creating a new string of spaces with the length the same length as match[0]. This would remove the regex replace within the loop. If performance isn't a high priority, this should work fine.

Removing %20 value from get method

Removing %20 in get method?
var c=new Array(a);
(eg: a={"1","2"}) window.location="my_details.html?"+ c + "_";
and in my_details.html :
var q=window.location.search;
alert("qqqqqqqqqqqqq " + q);
var arrayList = (q)? q.substring(1).split("_"):[];
var list=new Array(arrayList);
alert("dataaaaaaaaaaaa " + list + "llll " );
and in "list" its dusplaying me "1%202";
How can I remove this %20 =space value ??
Thanks
just use this:
alert("dataaaaaaaaaaaa " + decodeURIComponent(list) + "llll " );
This should decode the %20 to space
look here: http://www.w3schools.com/jsref/jsref_decodeURIComponent.asp
If there is a space in the parameter(s), then the %20 (URL Encoding) is necessary. You cannot pass a space in a GET request.
If you need to avoid this, use POST.
As far as I can see the problem is being introduced at this line:
window.location="my_details.html?"+ c + "_";
This could be written as:
window.location="my_details.html?"+ c.toString() + "_";
The default .toString() of a JavaScript Array would be to use a delimiter of ,, i.e.
var str = ["1", "2", "3"].toString(); // 1,2,3
In you example it appears that the delimiter being used is a space. This would have been changed by something changing the default behaviour of .toString() on the Array.prototype. Try using the following:
window.location="my_details.html?"+ c.join(",") + "_";
Better to use replace() method to replace %20 to space
list.replace("%20"," ");

Categories

Resources