【问题标题】:I want to add a single quotes and coma on every word in javascript我想在javascript中的每个单词上添加单引号和逗号
【发布时间】:2018-06-04 12:34:38
【问题描述】:

我想在 javascript 中的每个单词上添加单引号和逗号,示例如下。

如果我的输入值是

0000 
1111
2222
3333
4444

我在这个模式中需要上述内容。

'0000','1111','2222','3333','4444'

我尝试了几个例子,但都失败了。我的代码如下。

<!DOCTYPE html>
<html>

<body>

  <textarea id="oid"></textarea>
  <br>
  <button onclick="myFunction()">Try it</button>

  <p id="demo"></p>

  <script>
    function myFunction() {

      var a = document.getElementById("oid").value;

      a1 = a.split(" ");


      document.getElementById("demo").innerHTML = a1;
    }
  </script>

</body>

</html>

【问题讨论】:

  • 使用a1="'" + a.split(/\s+/).join("','") + "'";
  • 好的,我会检查并告诉
  • 它正在工作,谢谢

标签: javascript regex match


【解决方案1】:

我不是 100% 确定您正在寻找这个,但让我根据我的理解尝试一下。以逗号和撇号分隔的以空格分隔的一串数字。

function myFunction() {
  var a = "111 333 222 4545 321";
  var string = "'" + a.split(" ").join("','") + "'";

  console.log(string);
  document.getElementById("demo").innerHTML = string;
}

myFunction();
<div id="demo">

</div>

【讨论】:

    【解决方案2】:

    根据您的分隔符,您可以执行以下操作

    const textWithSpaces = "word1 word2 word3"
    const textWithLineBreaks = "word1\nword2\nword3";
    
    function doStuff(text, separator) {
      return text.split(separator).map(word => `'${word}'`).join(',');
    }
    
    console.log(doStuff(textWithSpaces, ' '));
    console.log(doStuff(textWithLineBreaks, '\n'));
    
    // Or with all kind of spaces
    
    console.log(doStuff(textWithSpaces, /\s+/));
    console.log(doStuff(textWithLineBreaks, /\s+/));

    【讨论】:

      【解决方案3】:

      function test(){
              var str = document.getElementById("hello").value;
              var el = document.getElementById("hel");
              var arr = str.split(" ");
              var res = "";
              for(var i = 0; i < arr.length; i++){
                  res += "'" + arr[i] + "', ";
      
              }
              el.innerHTML = res;
          }
          <textarea name="" id="hello" cols="30" rows="10"></textarea>
          <br>
          <button onclick="test()">Click Me</button>
      
          <p id="hel"></p>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多