Home > database >  Only first occurence of \n is replaced and not the other ones (want to replace all single occurence
Only first occurence of \n is replaced and not the other ones (want to replace all single occurence

Time:12-29

I am new to JavaScript and I was trying to create a tool that copies content from clipboard, replaces all single occurences of \n but leaves double new lines as they are, so that:

Hello
Hello

Hello

would become:

Hello Hello

Hello

This is the code I wrote:

<script>
    var text="";
    navigator.clipboard.readText().then((clipText) => (text = clipText));
</script>
<script>
  function clipboard(text) {
      var i = 0;
      var result = "";
      while (i < text.length) {
          if (i   1 < text.length && text.charAt(i) === "\n" && text.charAt(i 1) !== "\n") {
              if (text.charAt(i - 1) !== "\n") {
                  result = result   " ";
                  i  = 1;
              } else {
                  result = result   "\n";
                  i  = 1;
              }
          } else {
              result = result   text.charAt(i);
              i  = 1;
          }
      }
      navigator.clipboard.writeText(result).then();
  }
  window.addEventListener('load', function() {
      clipboard(text.replace("\r\n", "\n").replace("\r", "\n"))
  }) 
</script>

I am not able to understand why it only modifies the first occurance of \n and leaves other. I copied the following text:

roots and blindly abandon their core, but distinctive, competencies and core values. For
example, it is generally recognized that the reason “New Coke” failed was that it broke
away from the tried-but-true Coca-Cola traditional culture; and the reason Google so far
away from the tried-but-true Coca-Cola traditional culture; and the reason Google so far

And it gave back this:

roots and blindly abandon their core, but distinctive, competencies and core values. For example, it is generally recognized that the reason “New Coke” failed was that it broke

away from the tried-but-true Coca-Cola traditional culture; and the reason Google so far
 away from the tried-but-true Coca-Cola traditional culture; and the reason Google so far

I think the problem is with taking content from clipboard. This almost works. For example, copy the content from here and try opening this page. It doesn't work. But the same text works when inserted directly into a variable using the backquote symbols here.

CodePudding user response:

You can do the whole thing with a .replace(), using a negative lookbehind and a negative lookahead:

const str="This is a string\nwith a\nfew\nline\nfeeds in it.\n\nThe double ones are to be kept,\nbut\nthe single ones\nneed to be replaced\nby blanks!"

console.log(str);

const res=str.replace(/(?<!\n)\n(?!\n)/g," ");
console.log(res);

The negative lookbehind and lookahead make sure that the line feed in the center of the regular expression is a single one. Only then will it be replaced by a blank.

CodePudding user response:

To replace all single occurrences of \n with a different string in JavaScript, you can use the replace method of the String object. Here is an example of how you can use the replace method to replace all single occurrences of \n with a space:

let str = "This is a string\nwith multiple\nline breaks.";
str = str.replace(/\n/g, " ");
console.log(str); // "This is a string with multiple line breaks."

The replace method takes two arguments: the pattern to match (in this case, \n) and the replacement string (in this case, a space). The g flag at the end of the pattern specifies that the replacement should be global, meaning that all occurrences of the pattern should be replaced, rather than just the first one.

It's worth noting that the replace method is case-sensitive, so it will only replace \n and not \n, \N, or other variations. If you want to replace all variations of line breaks, you can use a more comprehensive pattern such as /\r?\n/g to match all types of line breaks.

CodePudding user response:

you can capture parts of the string and do the replacement, like:

text.replace(/(\w)\n(\w)/g, "$1 $2");
  • Related