如何用一个单词替换JavaScript中的最后一个字符?

时间:2017-05-11 10:06:22

标签: javascript

我检查了与此事有关的所有答案,但这些都不适用。我想建立一个简单的脚本,询问姓名和性别。如果某人将自己标识为女性,则该脚本将删除该字符串中的最后一个字符,并将其替换为“女性”一词,例如Agnes => Agnewoman,Maya => Maywoman等我知道字符串在JavaScript中是不可变的。我用一种口语来表达我的想法。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Let's get started</title>
<link href="../_css/site.css" rel="stylesheet">

<script>
var name = prompt("What's your name", " ");
var answer = prompt("Are you a woman?", " ");
</script>

</head>

<body>
<div class="wrapper">
  <header>
    JAVASCRIPT <span class="amp">and</span> jQUERY
  </header>
  <div class="content">
    <div class="main">
      <h1>Variables</h1>

      <script>
        if (answer == "yes" || answer == "Yes" || answer == "YES" || answer == "y" || answer == "Y"){
          document.write(...);
        } else {

        };
      </script>

    </div>
  </div>
</div>
</body>
</html>

6 个答案:

答案 0 :(得分:2)

奇怪的问题,但解决方案很简单: 删除最后一个字符并附加“女人”

name = name.substring(0,name.length - 1)+“woman”;

编辑:如果用户输入一个空字符串,这仍然有效,因为substring将负参数视为0。

答案 1 :(得分:1)

我会将您的性别问题更改为确认 - 然后您不必担心可以输入的不同选项。然后在javascript中就像检查答案是否为真一样简单(你可以使用if(answer == true)或下面的简写方式。

var name = prompt("What's your name", " ");
var namePortion = name.substring(0, name.length-1);

var answer = confirm("Are you a woman?");
if (answer){
  console.log(namePortion + 'woman')
} else {
  console.log(namePortion +'man')
};

答案 2 :(得分:1)

您还可以使用替换方法

name.replace(name.charAt(name.length-1), "women");

答案 3 :(得分:0)

您可以尝试这样的事情:

var gender = 'man';
if (answer == "yes" || answer == "Yes" || answer == "YES" || answer == "y" || answer == "Y") {
    gender = 'woman'
}

console.log(name.substring(0, name.length-1) + gender); 

答案 4 :(得分:0)

&#13;
&#13;
function showValue(){
var inp = document.getElementById("input_id").value;
var slp = document.getElementById("select_id").value;
if(slp== 'woman'){
document.getElementById("result").innerHTML = inp.slice(0,-1)+'woman';
}
else document.getElementById("result").innerHTML = inp;
}
&#13;
Name: <input id='input_id'>
gender : <select id='select_id'>
  <option value="man">man</option>
  <option value="woman">woman</option>
</select>
<button onclick='showValue()'>show</button>
<p id='result'></p>
&#13;
&#13;
&#13;

尝试切片(0,-1)

答案 5 :(得分:0)

您可以看到我提出的解决方案JSFiddle

if (answer == "yes" || answer == "Yes" || answer == "YES" || answer == "y" || answer == "Y"){
   name = name.slice(0, -1);
   document.write(name+"woman");
} else {
   document.write(name);
}