0

I need to snip out a substring from a string data which has a line break or '\n' in it.

var mainString = "HERE IS THE BEGIN OF LINE
PRINT HERE IS END OF LINE";

Please find the code below which I tried:

<!DOCTYPE html>
<html>
<body>

<p>Click the button</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var mainString = "HERE IS THE BEGIN 
OF LINE PRINT HERE IS END OF LINE";
 
    var n = mainString.indexOf("OF LINE");
 var str = "OF LINE";
 var result = mainString.substr(n + str.length);
    document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>

If I gets the data as an input from a textarea, is it possible to implement the backtick idea? If not, is there any alternate solution? please help! Thanks in advance.

AngularDoubts
  • 459
  • 2
  • 11
  • 30

1 Answers1

1

Your headline is inaccurate, the problem isn't with the substr() or indexOf() methods or that mainString contains a line break. The problem is that a string literal (using ' or ") with an actual line break is invalid syntax.

To solve this you can either use \n in your string literal in place of the actual line break:

var mainString = "HERE IS THE BEGIN\n OF LINE PRINT HERE IS END OF LINE";

Or if ES6 syntax is an option for you you can use a template literal instead, which allows actual line breaks:

var mainString = `HERE IS THE BEGIN
OF LINE PRINT HERE IS END OF LINE`;
Lennholm
  • 7,205
  • 1
  • 21
  • 30