0

I have to declare a variable but the value is coming runtime from some text strings.Can someone please suggest howto remove the spaces and line breaks so that variable is declare properly?

var view_Invoice= '

     invoice

';

It giving an error.

4
  • 4
    Trim it before putting it out. Else view_Invoic = view_Invoic.trim() Commented Jul 17, 2018 at 20:25
  • 1
    If you're using a programming language like Java, PHP, Python, Ruby, etc to generate Javascript code, use methods provided by these languages, for example, in Java you can use the method trim() as follow var view_Invoice = '<%= string.trim()%>' Commented Jul 17, 2018 at 20:27
  • 1
    @isherwood that dupe answer is wrong for this case. Commented Jul 17, 2018 at 20:28
  • 1
    Yeah... I think everyone except Ele is completely missing the question here. OP needs template literals (as long as IE support isn't needed) or a server side solution. Commented Jul 17, 2018 at 20:30

2 Answers 2

3

Trim it before putting it out in javascript. Changing the string delimiter also works in some browsers (which support ES6):

var view_Invoice= `

     invoice

`;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Sign up to request clarification or add additional context in comments.

Comments

1

The fundamental reason for why you're seeing this error is that the variable doesn't start with a valid character:

An identifier must start with $, _, or any character in the Unicode categories > “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”.

In your case, the easiest way to fix the problem will be to trim the white space from the beginning of the string. If you only want the whitespace at the beginning of the string to be removed, you can use

.replace(/^\s+/g, "")

but if you're happy for the whitespace at both the beginning and end of the whitespace removed you can use the .trim() function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.