js賦值時特殊字符完美處理方案

解決方案:javascript

一、創建WEB-INF/tags/format/enter.tag文件,其文件內容以下: html

<%@ tag body-content="scriptless" pageEncoding="utf-8" %><%@ attribute name="value" type="java.lang.String" required="true"%><%
	if(value != null) {
		int lengthh = value.length();
		StringBuffer filtered = new StringBuffer(lengthh);
		char prevChar = '\u0000';
		char c;
		for (int i = 0; i < lengthh; i++) {
			c = value.charAt(i);
			if (c == '"') {
				filtered.append("\\\"");
			} else if (c == '\'') {
			 	filtered.append("\\'");
			} else if (c == '\\') {
			 	filtered.append("\\\\");
			} else if (c == '\t') {
				filtered.append("\\t");
			} else if (c == '\n') {
				if (prevChar != '\r') {
					filtered.append("\\n");
				}
			} else if (c == '\r') {
				filtered.append("\\n");
			} else if (c == '\f') {
				filtered.append("\\f");
			} else if (c == '/') {
				filtered.append("\\/");
			} else {
				filtered.append(c);
			}
			prevChar = c;
		}
		value = String.valueOf(filtered);
	}	
	out.print(value);
%>

二、頁面運用,代碼示例以下: java

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib tagdir="/WEB-INF/tags/format" prefix="format" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<script type="text/javascript">
	function doTest() {
		//var testValue = '${valueFromJava }';// 這種複製若valueFromJava中含有特殊字符,此時會報錯
		var testValue = '<format:enter value="${s.content }" />';// 這種處理就……
	}
	</script>
  </head>
  
  <body>
    
  </body>
</html>

注:js中的特殊字符有:app

轉義序列 字符
\b 退格
\f 走紙換頁
\n 換行
\r 回車
\t 橫向跳格 (Ctrl-I)
\' 單引號
\" 雙引號
\\ 反斜槓
相關文章
相關標籤/搜索