1.

Remove element from an array in JavaScript

Answer»

Let’s say the following is our VARIABLE declaration of strings:

var val = "e\nx\na\nm\np\nl\ne";

To replace newlines, use the replace() method. The method replaces all occurrences of a CHARACTER in the given string. The replace(char1, char2)  has the following parameters:

  • char1: The character to be replaced
  • char2: The new character to be added in place of char1

Here the g flag on the regular EXPRESSION to perform a global match. The 2nd parameter is a space (“ “), which we want in place of new line (\n):

val = val.replace(/\n/g, " ");

The following is an example that replace newline with spaces:

<!DOCTYPE HTML> <html> <BODY> <script> var val = "e\nx\na\nm\np\nl\ne"; val = val.replace(/\n/g, " "); document.write("After removing new line: "+val); </script> </body> </html>

The output:

After removing new line: e x a m p l e


Discussion

No Comment Found