How to remove \n after JSON.stringfy? - javascript

I parse the data from website and try to change to a json object.
Here is my function:
function outPutJSON() {
for (var i = 0; i < movieTitle.length; i++) {
var handleN = movieContent[i];
console.log('===\n');
console.log(handleN);
data.movie.push({
mpvieTitle: movieTitle[i],
movieEnTitle: movieEnTitle[i],
theDate: theDate[i],
theLength: theLength[i],
movieVersion: movieVersion[i],
youtubeId: twoId[i],
content: movieContent[i]
});
};
return JSON.stringify(data);
}
console.log will print movieContent[0] like:
but i return JSON.stringfy(data);
it will become:
There are so many /n i want to remove it.
I try to change return JSON.stringfy(data); to this:
var allMovieData = JSON.stringify(data);
allMovieData = allMovieData.replace(/\n/g, '');
return allMovieData;
It's not working the result is the same.
How to remove /n when i use JSON.stringfy() ?
Any help would be appreciated . Thanks in advance.

In your data screenshots, you literally see "\n".
This probably means that the actual string doesn't contain a newline character (\n), but a escaped newline character (\\n).
A newline character would have been rendered as a linebreak. You wouldn't see the \n.
To remove those, use .replace(/\\n/g, '') instead of .replace(/\n/g, '')

just :=>
JSON.stringify(JSON.parse(<json object>))

JSON.stringify converts new lines (\n) and tab (\t) chars into string, so, when you will try to parse it, the string will contain those again.
So, you need to search the string \n, you can do that with something like that.
const stringWithNewLine = {
x: `this will conatin
new lines`
};
const json = JSON.stringify(stringWithNewLine);
console.log(json.replace(/\\n/g, ''))

I know this is an old question but it is always good to have options. You can use a string literal as a simple wrapper. The string literal will honor the string's line breaks, empty spaces etc. Like:
let jsonAsPrettyString = `${JSON.stringify(jsonObject, null, 2)}`;

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

How to trim empty space in the center of a string?

I have dynamically generated JSON file with data. Some of the data generate error of an invalid json:
SyntaxError: JSON.parse: bad control character in string literal at line 34447 column 24 of the JSON data
I located problems and some of these are
"live_href": "http:// http://google.com",
or
"login_pass": "bourdfthuk.midas.admin r3adqerds7one",
I already fixed whitespace at the beginning and end with .trim() but trim won't remove whitespace in the center of a string.
Use this
str.replace(/\s/g,'')
The g repeats for all whitespace instances and the s is for all white spaces and not just the literal characters.
I see what you are trying to do. In that case, you will have to loop through your string like so:
var word = "North Dakota Blah blah";
word = word.split(' ');
for (var x = 0; x < word.length; x++) {
if (word[x] === "") {
word.splice(x, 1);
x--;
}
}
word = word.join(' ');
console.log(word);
Working example: https://jsfiddle.net/85sj4ay6/2/
As someone already mentioned, your json is invalid, so you therefore cannot parse it into JSON. However, if it was valid, it would essentially work like this:
var myJson = {"login_pass": "bourdfthuk.midas.admin r3adqerds7one"};
myJson.login_pass = myJson.login_pass.replace(/ /g, '');
console.log(myJson);
Working example: https://jsfiddle.net/85sj4ay6/

Javascript replace regex any character

I am trying to replace something like '?order=height' and I know it can be easily done like this:
data = 'height'
x = '?order=' + data
x.replace('?order=' + data, '')
But the problem is that question mark can sometimes be ampersand.. What I really wish to do is make blank whether the first character is ampersand or question mark so basically whether
?order=height
&order=height
can be made a blank string
x.replace(/[&?]order=height/, '')
If data is string variable
x.replace(/[&?]order=([^&=]+)/, '')
Use regex for that .replace(/[?&]order=height/, '')
[?&] means any character from this list.
/ is start and end delimiter.
Please note that pattern is not enclosed as string with ' or ".
This is how you may do it. Create a RegExp object with
"[&?]order=" + match
and replace with "" using String.prototype.replace
function replace(match, str) {
regex = new RegExp("[&?]order=" + match,"g")
return str.replace(regex, "")
}
console.log(replace("height", "Yo &order=height Yo"))
console.log(replace("weight", "Yo ?order=weight Yo"))
console.log(replace("age", "Yo ?order=age Yo"))

Remove leading comma from a string

I have the following string:
",'first string','more','even more'"
I want to transform this into an Array but obviously this is not valid due to the first comma. How can I remove the first comma from my string and make it a valid Array?
I’d like to end up with something like this:
myArray = ['first string','more','even more']
To remove the first character you would use:
var myOriginalString = ",'first string','more','even more'";
var myString = myOriginalString.substring(1);
I'm not sure this will be the result you're looking for though because you will still need to split it to create an array with it. Maybe something like:
var myString = myOriginalString.substring(1);
var myArray = myString.split(',');
Keep in mind, the ' character will be a part of each string in the split here.
In this specific case (there is always a single character at the start you want to remove) you'll want:
str.substring(1)
However, if you want to be able to detect if the comma is there and remove it if it is, then something like:
if (str[0] == ',') {
str = str.substring(1);
}
One-liner
str = str.replace(/^,/, '');
I'll be back.
var s = ",'first string','more','even more'";
var array = s.split(',').slice(1);
That's assuming the string you begin with is in fact a String, like you said, and not an Array of strings.
Assuming the string is called myStr:
// Strip start and end quotation mark and possible initial comma
myStr=myStr.replace(/^,?'/,'').replace(/'$/,'');
// Split stripping quotations
myArray=myStr.split("','");
Note that if a string can be missing in the list without even having its quotation marks present and you want an empty spot in the corresponding location in the array, you'll need to write the splitting manually for a robust solution.
var s = ",'first string','more','even more'";
s.split(/'?,'?/).filter(function(v) { return v; });
Results in:
["first string", "more", "even more'"]
First split with commas possibly surrounded by single quotes,
then filter the non-truthy (empty) parts out.
To turn a string into an array I usually use split()
> var s = ",'first string','more','even more'"
> s.split("','")
[",'first string", "more", "even more'"]
This is almost what you want. Now you just have to strip the first two and the last character:
> s.slice(2, s.length-1)
"first string','more','even more"
> s.slice(2, s.length-2).split("','");
["first string", "more", "even more"]
To extract a substring from a string I usually use slice() but substr() and substring() also do the job.
s=s.substring(1);
I like to keep stuff simple.
You can use directly replace function on javascript with regex or define a help function as in php ltrim(left) and rtrim(right):
1) With replace:
var myArray = ",'first string','more','even more'".replace(/^\s+/, '').split(/'?,?'/);
2) Help functions:
if (!String.prototype.ltrim) String.prototype.ltrim = function() {
return this.replace(/^\s+/, '');
};
if (!String.prototype.rtrim) String.prototype.rtrim = function() {
return this.replace(/\s+$/, '');
};
var myArray = ",'first string','more','even more'".ltrim().split(/'?,?'/).filter(function(el) {return el.length != 0});;
You can do and other things to add parameter to the help function with what you want to replace the char, etc.
this will remove the trailing commas and spaces
var str = ",'first string','more','even more'";
var trim = str.replace(/(^\s*,)|(,\s*$)/g, '');
remove leading or trailing characters:
function trimLeadingTrailing(inputStr, toRemove) {
// use a regex to match toRemove at the start (^)
// and at the end ($) of inputStr
const re = new Regex(`/^${toRemove}|{toRemove}$/`);
return inputStr.replace(re, '');
}

How do I split a string that contains different signs?

I want to split a string that can look like this: word1;word2;word3,word4,word5,word6.word7. etc.
The string is from an output that I get from a php page that collects data from a database so the string may look different but the first words are always separated with ; and then , and the last words with .(dot)
I want to be able to fetch all the words that ends with for example ; , or . into an array. Does someone know how to do this?
I would also like to know how to fetch only the words that ends with ;
The function ends_with(string, character) below works but it takes no regard to whitespace. For example if the word is Jonas Sand, it only prints Sand. Anybody knows how to fix this?
Probably
var string = "word1;word2;word3,word4,word5,word6.word7";
var array = string.split(/[;,.]/);
// array = ["word1", "word2", "word3", "word4", "word5", "word6", "word7"]
The key is in the regular expression passed to the String#split method. The character class operator [] allows the regular expression to select between the characters contained with it.
If you need to split on a string that contains more than one character, you can use the | to differentiate.
var array = string.split(/;|,|./) // same as above
Edit: Didn't thoroughly read the question. Something like this
var string = "word1;word2;word3,word4,word5,word6.word7";
function ends_with(string, character) {
var regexp = new RegExp('\\w+' + character, 'g');
var matches = string.match(regexp);
var replacer = new RegExp(character + '$');
return matches.map(function(ee) {
return ee.replace(replacer, '');
});
}
// ends_with(string, ';') => ["word1", "word2"]
var myString = word1;word2;word3,word4,word5,word6.word7;
var result = myString.split(/;|,|./);

Categories

Resources