The substitution of slashes and backslashes in Java,javascript

Source: Internet
Author: User

Java:

In different systems, the path delimiter is different, so we need to make a judgment, and switch the delimiter;

The ReplaceAll method in the string class is as follows:

String.replaceall (String regex,string replacement), the ReplaceAll () method uses 4 backslashes to denote a backslash;

1. Java replaces the backslash (\) in the string with a double slash (\ \)

ReplaceAll is used in the regular expression, so the string escaped once, is escaped once, so a diagonal carry to write 4, such as: ReplaceAll ("\\\\", "\\\\\\\\");

2.java Replace the backslash (\) in the string with a slash (/)

ReplaceAll ("\\\\ ", "/");

3.java Replace the slash (/) in the string with a backslash (\)

ReplaceAll ("/", "\\\\");


For example str1= "AA\BBB"; str2= "AA ' BBB" to replace str1= "AA\\BBB", str2= "Aa\ ' BBB";
This must be replaced:
STR1 = Str1.replaceall ("\\\\", "\\\\\\\\");
STR2 = Str2.replaceall ("'", "\\\\ '");
The reasons are as follows:
The ReplaceAll () method of String is actually used to match the regular expression rules, \\\\,java resolves to \ \ to the regular expression, the regular expression goes through a conversion, the \ \ is converted to \; that is, Java has to use regular to represent a \. Must be written in 4 \; If you want to represent \ \, then write 8 \; So if written as: str1 = Str1.replaceall ("\ \", "\\\\"), the regular expression error will be reported.


javascript:

stringObj.replace (Rgexp, ReplaceText)   where stringobj is a string reexp Span style= "line-height:20.7999992370605px" > (REGEXP) can also be a string replacetext is an alternative to the found string.

1. JavaScript replaces the backslash (\) in a string with a double slash (\ \)

Replace (/\\/g, "\\\\");

2.JavaScript replaces the backslash (\) in the string with a slash (/)

Replace (/\\/g, "\");

3.JavaScript replaces a slash (/) in a string with a backslash (\)

Replace (/\//g, "\ \");


The substitution of slashes and backslashes in Java,javascript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.