2016-04-13 22 views
-1

但是,我仍然在代码中的特定点处提供空字符串。指示说要从字符串中删除所有句点,逗号和连字符

下面是代码:

beg=document.twocities.begins.value; 
len_beg=beg.length; 

var beg = beg.replace(/.,-/g," "); 

1.

var beg_array=beg.split(" "); 
ans1.innerHTML=beg_array.length; 

2.

ans2.innerHTML=beg_array[0]+" "+beg_array[116]; 

3.

ans3.innerHTML=beg_array; 

4.

beg_upper=beg.toUpperCase(); 
ans4.innerHTML=beg_upper; 

这里是输出:

1. 116 
2. It undefined 
3. It,was,the,best,of,times,,it,was,the,worst,of,times, it,was,the,age,of,wisdom,,it,was,the,age,of,foolishness, it,was,the,epoch,of,belief,,it,was,the,epoch,of,incredulity,, it,was,the,season,of,Light,,it,was,the,season,of,Darkness,, it,was,the,spring,of,hope,,it,was,the,winter,of,despair,, we,had,everything,before,us,,we,had,nothing,before,us, we,were,all,going,direct,to,Heaven,,we,were,all,going,direct,the,other,way,-- in,short,,the,period,was,so,far,like,the,present,period,, that,some,of,its,noisiest,authorities,insisted,on,its,being,received,, for,good,or,for,evil,,in,the,superlative,degree,of,comparison,only. 
4. IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES, IT WAS THE AGE OF WISDOM, IT WAS THE AGE OF FOOLISHNESS, IT WAS THE EPOCH OF BELIEF, IT WAS THE EPOCH OF INCREDULITY, IT WAS THE SEASON OF LIGHT, IT WAS THE SEASON OF DARKNESS, IT WAS THE SPRING OF HOPE, IT WAS THE WINTER OF DESPAIR, WE HAD EVERYTHING BEFORE US, WE HAD NOTHING BEFORE US, WE WERE ALL GOING DIRECT TO HEAVEN, WE WERE ALL GOING DIRECT THE OTHER WAY -- IN SHORT, THE PERIOD WAS SO FAR LIKE THE PRESENT PERIOD, THAT SOME OF ITS NOISIEST AUTHORITIES INSISTED ON ITS BEING RECEIVED, FOR GOOD OR FOR EVIL, IN THE SUPERLATIVE DEGREE OF COMPARISON ONLY. 
+2

发布您的代码作为文本或SO片段。 –

+0

建议阅读一个很好的正则表达式教程,例如MDN上的教程。看看角色类。 –

回答

0

移除所有,.-(使用[]列表)

var string = "Th.is,, ,,is .so---me- -ni-ce. ..str,in.g"; 
 
var fixed = string.replace(/[,.-]/g, ''); 
 
alert(fixed); // "This is some nice string"

移除所有,.-(使用|的替代品。在这里,你需要\逃避.令牌)

var string = "Th.is,, ,,is .so---me- -ni-ce. ..str,in.g"; 
 
var fixed = string.replace(/,|\.|-/g, ''); 
 
alert(fixed); // "This is some nice string"

删除任何东西,但A-Z A-Z charaters和\s空间

var string = "Th.is,, ,,is .so---me- -ni-ce. ..str,in.g"; 
 
var fixed = string.replace(/[^a-zA-Z\s]/g, ''); 
 
alert(fixed); // "This is some nice string"

删除任何东西,但A- Z(i不区分大小写标志)charaters和\s空间

var string = "Th.is,, ,,is .so---me- -ni-ce. ..str,in.g"; 
 
var fixed = string.replace(/[^a-z\s]/ig, ''); 
 
alert(fixed); // "This is some nice string"

+0

工作正常!谢谢! – Deniz

+0

@Deniz不用客气 –

相关问题