繁体   English   中英

使用 javascript 用逗号分隔值替换 Hashtag 分隔值

[英]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

您可以将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>

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM