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