最近面试一个前端岗位,出了一个面试题。
问题:给定任意英文段落,段落内可能包含多组单引号组合,要求将单引号组合中的左单引号字符 ’ 替换为 ` ,右单引号字符 ’ 保持不变?
实现方式:
<!DOCTYPE html>
<html lang="zh_cn">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="js/vue.min.js"></script>
</head>
<body>
<div>
<textarea cols="120" rows="10" id="inputText"></textarea>
<button id="replaceButton">替换单引号</button>
</div>
<div>
<h1>替换结果:</h1>
<p id="result"></p>
</div>
</body>
<script type="text/javascript">
window.onload = function(){
document.getElementById("replaceButton").addEventListener("click", this.replaceMsg, false);
};
function replaceMsg(){
var forReplace = document.getElementById("inputText").value;
if(forReplace === "" || forReplace === null || forReplace === undefined){
alert("请输入英文字段");
return;
}
var strArray = forReplace.split(" ");
var result = "";
for(var i = 0 ; i < strArray.length ; i ++){
if(strArray[i].indexOf("'") !== -1) {
if (/\w/.test(strArray[i].substring(0, (strArray[i].indexOf("'")))) &&
/\w/.test(strArray[i].substring((strArray[i].indexOf("'") + 1)))) {
result += strArray[i] + " ";
}else{
if(strArray[i].substring(0, (strArray[i].indexOf("'"))) === ""){
// 表示字符的开始
result += "`" + strArray[i].substring(strArray[i].indexOf("'") + 1) + " ";
}else{
if(strArray[i].substring(strArray[i].indexOf("'") + 1) === ""){
result += strArray[i] + " ";
}
}
}
}else{
result += strArray[i] + " ";
}
}
document.getElementById("result").innerHTML = result;
}
</script>
</html>