从字符串

时间:2016-04-13 00:56:31

标签: javascript string replace

但是,尝试了这些,我仍然在代码中的非常具体的位置提出空字符串。

以下是代码:

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. 

1 个答案:

答案 0 :(得分:1)

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

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

删除所有,.-(使用|替代方案。您需要\转义.令牌

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

删除除a-z A-Z字符和\s空格

之外的任何内容

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

删除除a-z(i不区分大小写的标记)以及\s空格

之外的任何内容

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