saurabh
saurabh

Reputation: 79

How to replace new line character with comma in angular

I have one textarea field in which the user can enter input in a new line as well as comma-separated values. so when I m sending values in API /n is appended in case of the new line and same /n is visible on detail page which I don't want. below is the example of user input.

Ex-1

ABC

red

test,blue

Ex-2

abc,blue,

green,red

test

I want each time to check for new line break and comma, my mean is to say if user enter values in new line then replace newline character with a comma and if a comma is already appended then keep it as it is.

Expected output

Ex-1

ABC,red,test,blue

Ex-2

abc,blue,green,red,test

Below is my code

createData(data) {
    const Obj = {};   
    if (data.enum && data.value_type === 'Enum') {
        Obj['values'] = data.enum.split(',');
    }    
    console.log(Obj,"constraint");
    return Obj;
  }

Upvotes: 2

Views: 4181

Answers (3)

Wojciech Fornal
Wojciech Fornal

Reputation: 1563

Another approach is to intercept input every time user enters character. With this method you avoid parsing whole text over and over again with every keystroke (including redundant ones).

Following is a simple piece of code that substitutes newlines and spaces with commas on the fly. Assuming you have a textarea with id textArea somewhere in your HTML.

const textArea = document.getElementById('textArea');

const parseText = function parseText(e) {

  if (e.keyCode === 13 || e.keyCode === 32) {
  
    e && e.preventDefault();
    
    let text = textArea.value;
    let curStart = textArea.selectionStart;
    let curEnd = textArea.selectionEnd;

    if (curStart == text.length && curEnd == text.length && !text.endsWith(',')) {
      text += ',';
      textArea.value = text;
    }

  }


}

textArea.addEventListener('keydown', parseText);

Regards

Upvotes: 0

User863
User863

Reputation: 20039

Using regex split()

Regex Demo

const str1 = `ABC

red

test,blue`;

const str2 = `abc,blue,

green,red

test`;

console.log(str1.split(/[,\n]+\s+/g).join(','))
console.log(str2.split(/[,\n]+\s+/g).join(','))

Upvotes: 1

Rajan
Rajan

Reputation: 1568

You need first split the string with a newline character, Remove any empty string from the array once it's done joined it with ,. Also, we need to take care of some double comma as string contain a comma.

var str = `ABC

red

test,blue`;

var str2 = `abc,blue,

green,red

test`;
formateString(str);
formateString(str2);

function formateString(str) {

  var strArray = str.split("\n");
  strArray = strArray.filter((item) => {
    return item !== '';
  });
  console.log(strArray.join(",").split(",,").join(","));
}

Upvotes: 1

Related Questions