Asked  7 Months ago    Answers:  5   Viewed   36 times

I want to initialize a String in Java, but that string needs to include quotes; for example: "ROM". I tried doing:

String value = " "ROM" ";

but that doesn't work. How can I include "s within a string?

 Answers

49

In Java, you can escape quotes with :

String value = " "ROM" ";
Tuesday, June 1, 2021
 
Freddie
answered 7 Months ago
94
@FXML
private void handleButtonAction(ActionEvent event) {
    System.out.println("You clicked me!");
    label.setText("Hello World!");
    //Here I want to swap the screen!

    Stage stageTheEventSourceNodeBelongs = (Stage) ((Node)event.getSource()).getScene().getWindow();
    // OR
    Stage stageTheLabelBelongs = (Stage) label.getScene().getWindow();
    // these two of them return the same stage
    // Swap screen
    stage.setScene(new Scene(new Pane()));
}
Friday, June 18, 2021
 
msg
answered 6 Months ago
msg
32

What's tripping you up is the </script>. The HTML parser doesn't recognize Javascript strings or nested <script> tags, so it's interpreting that as the closing tag for the initial <script>. That is, this part of the document is parsed as:

<script>                (open tag)
    alert("<script>     (text node - contents of the script)
</script>               (close tag)
");                     (text node - plain text)

The second </script> is ignored, as there's no other <script> tag for it to close.

To work around this, break up </script so that the HTML parser doesn't see it. For instance:

alert("<script></script>");

or:

alert("<script><" + "/script>");

or just put the code in an external Javascript file. This issue only arises for inline scripts.

Thursday, June 24, 2021
 
codingb
answered 6 Months ago
43

The thing is that .replace() does not modify the string itself, so you should write something like:

strInputString = strInputString.replace(...

It also seems like you're not doing character escaping correctly. The following worked for me:

strInputString = strInputString.replace(/'/g, "\'");
Sunday, August 1, 2021
 
penpen
answered 4 Months ago
90

First of all, if you are trying to encode apostophes for querystrings, they need to be URLEncoded, not escaped with a leading backslash. For that use URLEncoder.encode(String, String) (BTW: the second argument should always be "UTF-8"). Secondly, if you want to replace all instances of apostophe with backslash apostrophe, you must escape the backslash in your string expression with a leading backslash. Like this:

"This is' it".replace("'", "\'");

Edit:

I see now that you are probably trying to dynamically build a SQL statement. Do not do it this way. Your code will be susceptible to SQL injection attacks. Instead use a PreparedStatement.

Saturday, September 4, 2021
 
Rod
answered 3 Months ago
Rod
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share