Replace line breaks without using the \r\n characters

Currently working on a new website and exploring some JavaScript functionalities. Being a beginner in this field, I apologize if my question seems basic :)

I have a JSON string with line breaks that are causing issues when trying to parse it into a JSON object. I attempted to remove the line breaks using:

stringJSON.replace(/(\r\n|\r|\n)+/, '');

However, despite applying this code, the line breaks still persist when I alert the string.

Any suggestions or alternatives?

Thank you in advance,

Wiwi :)

JSON:

[
    {
        "key0": "value 0",
        "key1": "value 1",
        "key2": "value 2"
    },
    {
        "key0": "value 0",
        "key1": "value 1",
        "key2": "value 2"
    }
]

Answer №1

Make sure to assign the result of the replace operation back to the stringJSON variable if your intention is to update its value.

stringJSON = stringJSON.replace(/(\r\n|\r|\n)+/g, '');

Remember that in JavaScript, strings are immutable, so the original string remains unchanged after a replace operation.

Keep in mind that using the global flag (g) in the regex allows for replacing multiple occurrences. Without it, only the first instance would be replaced.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript's ability to utilize local files

Has anyone successfully performed local file manipulation using JavaScript without any installation requirement like Adobe AIR? I am specifically interested in reading the contents of a file and writing them to another file. I am not concerned about permi ...

Tips for updating a plugin from phonegap 2.5 to the most recent version 3.1, and the steps to follow when including a new plugin in phonegap

$('#sendSms').click(function(e){ alert("Sending SMS in progress");//After this alert, I encountered continuous errors and couldn't determine the root cause var smsInboxPlugin = cordova.require('cordova/plugin/smsinboxplugin'); ...

Tidying up Ajax JSON GET Request in Django

Currently, I am utilizing AJAX to load some data on my website. While I can successfully load the data, it appears in a json format which is not very user-friendly. Any suggestions on how I can make this data display cleaner and easier for users to read? ...

Using JavaScript to delete text and send data to the server

<script type="text/javascript"> function removeLink() { document.getElementById("tab2").deleteRow(i); } </script> </head> <body> <form action="forth.php" method="post"> <table width="600" border="1" id="tab2"> &l ...

Creating a dialog box that effectively blocks user interaction

Is it possible to implement a blocking dialog box with JavaScript/JQuery/Ajax? I've been working with the JQuery UI dialog box, but using it asynchronously with callback functions has made it more complicated than expected. For example: ans1 = confi ...

"Converting array into a string in TypeScript/Javascript, but unable to perform operations

After generating a string with the correct structure that includes an array, I am able to navigate through the JSON on sites like However, when attempting to access the array, it turns out that the array itself is null. Here is the scenario: Firstly, th ...

Angular: When $scope variable is modified, a blank page issue arises

In my Angular application, I have a template called viewAll.html that is displayed after clicking on a link. This template fetches data via AJAX using scope variables. However, I encountered an issue where updating these scope variables through AJAX cause ...

What is the best way to loop through JSON descendants using Python?

I am currently facing an issue while trying to loop through a JSON response obtained from the Google Sheets API. My objective is to extract the values of each title such as 'Chapter 1', 'Chapter 2', and so on, but I am struggling to go ...

Iterate through every row in the table in order to carry out a mathematical operation

I have created a jQuery function to add a table dynamically: $(document).on('click', '.add', function(){ var html = ''; html += '<tbody><tr>'; html += '<td><select name="product_name[]" cla ...

Discovering pairs of numbers that are not next to each other in an array that has not been

When working with an array of unsorted numbers, the goal is to identify and extract pairs of elements that are not consecutive. Input [2,3,4,5,9,8,10,13] Desired output (2,5)(8,10)(13,13) To achieve this: Input = [2,3,4,5,9,8,10,13] If we arrange the num ...

JSON geometry imported is not following the movement of the bones

After importing a model into my Three.js scene, I encountered an issue where the bones can be moved and rotated successfully, but the model's geometry does not follow these bone movements. For importing the JSON file and adding it to the scene, here ...

Attempting to initiate factory function

I encountered an issue with the following error message: TypeError: MyTheme.register is not a function This error occurred when I tried to invoke this function from my package in the controllers folder. I attempted the following: vm.register = function() ...

pg-promise makes it easy to use named parameters with nested objects

Is it feasible to access nested objects while utilizing named parameters in pg-promise? Take a look at this example: var obj = { name: 'John', address: { postcode: 'abc' } }; db.query('SELECT * FROM users WHER ...

Mongoose not functioning correctly when attempting to remove items from an array that meet a certain condition

In my document, I have a property called weeks which is an Array containing Objects. [ { "time": [ "06", "00" ], "active": false, "reason": " ...

"Unending loop conundrum triggered by React's useEffect

Currently, I am facing an issue where one of the buttons in my useEffect hook is causing infinite warnings. The warning message states: "Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect ...

The issue of undefined 'this' in Typescript AngularJS

I have developed a TypeScript service that looks something like this: export default class MyService { constructor(private $http: ng.IHttpService, ...) {} method1(data : any) : void { this.$http(...) } method2(data : any) : void ...

Having difficulty sorting data with Firebase in a VueJS project

I'm a newcomer to VueJS and I've encountered an issue when attempting to call the OrderBy method using VueJS. My basic application is fetching a simple array of items that are being displayed in a table: <!DOCTYPE html> ...

Combining JS Tree and Datatables for Enhanced Functionality

I am facing a challenge on my webpage where I have two columns. The left column consists of a checkbox jstree, while the right column contains a table using datatables. Both the table rows and tree are loaded at the start. My goal is to display a row when ...

The process of matching the full names of the source and destination Strings in Node.js

Need assistance comparing two strings with a third string in a JSON Array for full names var source = intentObj.slots.toPlazaName.value.toString(); // Jaipur var destination = intentObj.slots.fromPlazaName.value.toString(); // Kishangarh Compare with t ...

I need help determining the starting date and ending date of the week based on a given date

I am looking to determine the starting date (Monday) and ending date of a specified date using Javascript. For instance, if my date is 2015-11-20, then the starting date would be 2015-11-16 and the ending date would be 2015-11-21. ...