[英]JavaScript replace all comma in a string
I want to convert all comma in below string to space or say blank, i tried below code which is only taking care of first comma, I tried global indicator /g as well but that do nothing. 我想将下面的字符串中的所有逗号转换为空格或说空白,我尝试下面的代码只处理第一个逗号,我尝试了全局指标/ g但是什么也没做。
What I am doing wrong? 我做错了什么?
var str="D'Or, Megan#LastName Jr., FirstName#BMW, somename#What, new";
str=str.replace(',','');
alert(str)
D'Or Megan#LastName Jr., FirstName#BMW, somename#What, new D'Or Megan#LastName Jr.,FirstName#BMW,somename#What,new
D'Or Megan#LastName Jr. FirstName#BMW somename#What new D'Or Megan#LastName Jr. FirstName#BMW somename#新的
To replace any given string u need to use regular expressions. 要替换任何给定的字符串,您需要使用正则表达式。 You need to use a RegExp
Object to ensure crossbrowser compatibility. 您需要使用RegExp
对象来确保crossbrowser兼容性。
The use of the flags parameter in the String.replace method is non-standard. String.replace方法中flags参数的使用是非标准的。 For cross-browser compatibility, use a RegExp object with corresponding flags. 对于跨浏览器兼容性,请使用带有相应标志的RegExp对象。
//Init
var str = "D'Or, Megan#LastName Jr., FirstName#BMW, somename#What, new";
var regex = new RegExp(',', 'g');
//replace via regex
str = str.replace(regex, '');
//output check
console.log(str); // D'Or Megan#LastName Jr. FirstName#BMW somename#What new
See that fiddle: http://jsfiddle.net/m1yhwL3n/1/ example. 看到那个小提琴: http : //jsfiddle.net/m1yhwL3n/1/的例子。 Thats how it will work fine for all browsers. 这就是它如何适用于所有浏览器。
您需要以下列方式使用全局选项:
str=str.replace(/,/g,'');
Try this code, 试试这段代码,
var str="D'Or, Megan#LastName Jr., FirstName#BMW, somename#What, new";
val=str.replace(/,/g, '');
alert(val);
My Bad i was using comma for regex 我的坏我正在使用逗号进行正则表达式
wrong str=str.replace('/,/g',''); 错误的str = str.replace('/,/ g','');
good str=str.replace(/,/g,''); good str = str.replace(/,/ g,'');
Thanks all for correct this..I will add points for all of you. 谢谢大家的正确答案..我会为你们所有人添加积分。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.