使用javascript将井号分隔的值替换为逗号分隔的值

问题描述 投票:2回答:2

试图转弯..

#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

javascript php html str-replace
2个回答
3
投票

您可以在回调函数中使用String#replace,该函数可用于区分替换值


1
投票

我想在它们前面有<!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子字符串,然后用逗号分隔#

© www.soinside.com 2019 - 2024. All rights reserved.