试图转弯..
#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
子字符串,然后用逗号分隔#
: