使用 javascript 将标签分隔值替换为逗号分隔值

Replace Hashtag-separated values with Comma-separated values using javascript

正在尝试转..

#one #two #three

进入

one, two, three

几乎成功了,但错过了第一个..

代码..

<!DOCTYPE html>
<html>
<body>

<p>Click the button to replace " #" with ", " in the paragraph below:</p>

<p id="demo">#one #two #three</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  var str = document.getElementById("demo").innerHTML; 
  var res = str.replace(/ #/g, ", ");
  document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

https://www.w3schools.com/code/tryit.asp?filename=GALOV6REXR1C

我会 .match 子字符串,它们前面有一个 #,然后用逗号 .join

const str = '#one #two #three';
const arr = str.match(/(?<=#)\S+/g);
const output = arr.join(', ');
console.log(output);

没有lookbehind,如果主题标签由空格分隔,由空格分隔,.map从每个删除第一个哈希字符,然后加入:

const str = '#one #two #three';
const output = str
  .split(' ')
  .map(hashtag => hashtag.slice(1))
  .join(', ');
console.log(output);

您可以将 String#replace 与回调一起使用,其中该函数可用于区分替换值

<!DOCTYPE html>
<html>

<body>

  <p>Click the button to replace " #" with ", " in the paragraph below:</p>

  <p id="demo">#one #two #three</p>

  <button onclick="myFunction()">Try it</button>

  <script>
    function myFunction() {
      var str = document.getElementById("demo").innerHTML;
      var res = str.replace(/^#|( #)/g, (_, m1) => m1 ? ", " : '');
      document.getElementById("demo").innerHTML = res;
    }
  </script>

</body>

</html>