Node.JS not appending string weird bug? - javascript

function getStatementValue(view, statement){ // vars "#extends('parentview') ", 'extends'
var parentname = "";
view.replace(new RegExp(/\B#\w+\('([^(')\W]+)'\)\s/, 'm'), function(occurance){
parentname = occurance.replace('#' + statement + '(\'', '')
.replace('\')', "");
console.log(parentname) // parentview
console.log(parentname + 'test') // testntview <- unexpected result
});
return parentname;
}
I've got no clue to how that result is appearing.
when I add the string as shown in console.log, it replaces the string from the beginning, almost like it's re-assigning the memory space. Is this supposed to be happening? How do I return the correct parentviewtest result?

parentname = occurance.replace('#' + statement + '(\'', '')
.replace('\')', "").trim();
Solved it by adding a .trim() to the string modification. My input included invisible \r and \n characters that I was unaware of.
Thanks to #JaromandaX for spotting that out

Related

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

Replace null bytes

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));

Recombine capture groups in single regexp?

I am trying to handle input groups similar to:
'...A.B.' and want to output '.....AB'.
Another example:
'.C..Z..B.' ==> '......CZB'
I have been working with the following:
'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1")
returns:
"....."
and
'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$2")
returns:
"AB"
but
'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1$2")
returns
"...A.B."
Is there a way to return
"....AB"
with a single regexp?
I have only been able to accomplish this with:
'...A.B.'.replace(/(\.*)([A-Z]*)/g, "$1") + '...A.B.'.replace(/(\.*)([A-Z]*)/g, "$2")
==> ".....AB"
If the goal is to move all of the . to the beginning and all of the A-Z to the end, then I believe the answer to
with a single regexp?
is "no."
Separately, I don't think there's a simpler, more efficient way than two replace calls — but not the two you've shown. Instead:
var str = "...A..B...C.";
var result = str.replace(/[A-Z]/g, "") + str.replace(/\./g, "");
console.log(result);
(I don't know what you want to do with non-., non-A-Z characters, so I've ignored them.)
If you really want to do it with a single call to replace (e.g., a single pass through the string matters), you can, but I'm fairly sure you'd have to use the function callback and state variables:
var str = "...A..B...C.";
var dots = "";
var nondots = "";
var result = str.replace(/\.|[A-Z]|$/g, function(m) {
if (!m) {
// Matched the end of input; return the
// strings we've been building up
return dots + nondots;
}
// Matched a dot or letter, add to relevant
// string and return nothing
if (m === ".") {
dots += m;
} else {
nondots += m;
}
return "";
});
console.log(result);
That is, of course, incredibly ugly. :-)

How can I find a specific string and replace based on character?

I'm trying to find a specific character, for example '?' and then remove all text behind the char until I hit a whitespace.
So that:
var string = '?What is going on here?';
Then the new string would be: 'is going on here';
I have been using this:
var mod_content = content.substring(content.indexOf(' ') + 1);
But this is not valid anymore, since the specific string also can be in the middle of a string also.
I haven't really tried anything but this. I have no idea at all how to do it.
use:
string = string.replace(/\?\S*\s+/g, '');
Update:
If want to remove the last ? too, then use
string = string.replace(/\?\S*\s*/g, '');
var firstBit = str.split("?");
var bityouWant = firstBit.substring(firstBit.indexOf(' ') + 1);

SyntaxError: missing ; before statement

I am getting this error :
SyntaxError: missing ; before statement
Why would I get that from this code? How can I get around this ?
var $this = $("input");
foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
}));
Looks like you have an extra parenthesis.
The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.
foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
})
too many ) parenthesis remove one of them.
Or you might have something like this (redeclaring a variable):
var data = [];
var data =
I got this error, hope this will help someone:
const firstName = 'Joe';
const lastName = 'Blogs';
const wholeName = firstName + ' ' lastName + '.';
The problem was that I was missing a plus (+) between the empty space and lastName. This is a super simplified example: I was concatenating about 9 different parts so it was hard to spot the error.
Summa summarum: if you get "SyntaxError: missing ; before statement", don't look at what is wrong with the the semicolon (;) symbols in your code, look for an error in syntax on that line.

Categories

Resources