[英]Replace all occurrences of ',' to space in a string
I want to replace all the occurence of ',' to ' ' and '{' to ' ' and ' }' to ' '.我想将所有出现的 ',' 替换为 ' ' 和 '{' 替换为 ' ' 和 ' }' 替换为 ' '。
By using replace, I can only replace the first occurrence of ',' and I want to replace all occurrences.通过使用替换,我只能替换第一次出现的“,”,我想替换所有出现的地方。
const summary_data=[{Geo: "US West", MeetingHash: "Hold/Uncategorized", count: 65}, {Geo: "NSU", MeetingHash: "Hold/Uncategorized", count: 9}, {Geo: "US East", MeetingHash: "Hold/Uncategorized", count: 3}]; var str=""; $.each(summary_data, function (key, entry) { str += JSON.stringify(entry).replace(","," ") + "\n"; }); console.log(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Hey replace
accepts regex and you can put global flag on it like this:嘿
replace
接受正则表达式,您可以像这样在其上放置全局标志:
replace(/,/g, " ")
This will replace all occurrences of "," with " "这会将所有出现的“,”替换为“”
You need to create a regular expression with the global modifier.您需要使用全局修饰符创建正则表达式。 Use the pipe (
|
) to match either a comma or curly brace.使用 pipe (
|
) 匹配逗号或花括号。
str += JSON.stringify(entry) .replace(/,|\{|\}/g," ") + "\n";
const summary_data=[{Geo: "US West", MeetingHash: "Hold/Uncategorized", count: 65}, {Geo: "NSU", MeetingHash: "Hold/Uncategorized", count: 9}, {Geo: "US East", MeetingHash: "Hold/Uncategorized", count: 3}]; var str=""; $.each(summary_data, function (key, entry) { str += JSON.stringify(entry).replace(/,|\{|\}/g," ") + "\n"; }); console.log(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try this:尝试这个:
var exampleStr = "{example, string}";
// Returns " example string "
exampleStr.replace(/,/g, " ").replace(/{/g, " ").replace(/}/g, " ");
// Returns "example string"
exampleStr.replace(/,/g, "").replace(/{/g, "").replace(/}/g, "");
let str = JSON.stringify(summary_data).split(',').join(' ').split('{').join(' ').split('}').join('')
No regex answer没有正则表达式答案
From the String.prototype.replace() docs at MDN来自MDN 的 String.prototype.replace() 文档
... If
pattern
is a string, only the first occurrence will be replaced....如果
pattern
是一个字符串,只有第一次出现将被替换。
To get around this limitation either use replaceAll()
or a regular expression ie replace(/,/g, ' ')
要解决此限制,请使用
replaceAll()
或正则表达式,即replace(/,/g, ' ')
string.replace(searchvalue, newvalue)
where searchvalue can be string or RegExp, and the below example to perform a global replacement. string.replace(searchvalue, newvalue)
其中 searchvalue 可以是字符串或正则表达式,下面的示例执行全局替换。
JSON.stringify(entry)
.replace(/\,/g, " ") // replace comma's with spaces
.replace(/\s+/g, " ").trim() //remove extra spaces with only one and trim
.replace(/[\{\}]/g, "") //To replace multiple
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.