简体   繁体   English

如何分割javascript字符串,仅保留字符

[英]how to split javascript string, leaving just the characters

I would like to know how can I split a long string to an array of words. 我想知道如何将长字符串拆分为单词数组。 I would like to ignore/remove all the non alphabethic characters. 我想忽略/删除所有非字母字符。

For example: If I have the next string: "free games @ somewhere, visit us. don't want to miss out?, then go ahead & visit us @ somewhere-to-download-from." 例如:如果我输入下一个字符串:“在某个地方可以免费游戏,请访问我们。不想错过??然后继续并在某个地方进行下载,以下载我们的内容。”

I would like it to be splitted to: "free,games,somewhere,visit,us,don't,want,to,miss,out,then,go,ahead,visit,us,somewhere,to,down,load,from" 我希望将其拆分为:“免费,游戏,某处,访问,我们,不要,想要,到,错过,出去,然后,去,前进,访问,我们,某处,到,向下,加载,从”

In the end I will have an array size 20 that on each cell it holds one word of the above. 最后,我将得到一个数组大小20,该数组大小在每个单元格上都包含一个以上的字。

Try: 尝试:


var chk = str.split(/[^a-z']+/i);
console.log(chk);

Use the Javascript split function with a regular expression. 将Javascript split功能与正则表达式一起使用。 Example: 例:

var str = "free games @ somewhere, visit us. don't want to miss out?, then go ahead & visit us @ somewhere-to-download-from.";
alert(str.split(/[^a-z]+/i));

This should work: 这应该工作:

str = "free games @ somewhere, visit us. don't want to miss out?, then go ahead & visit us @ somewhere-to-download-from.";
str = str.replace(/[^a-z]/gi," ").replace(/ {1,}/g," ").split(" ");
document.write(str);
function specialSplit(str){
    var reqArray = new Array();
    var len = str.length;
    var tempStr = "";
    for(var i=0;i<len;i++){
        if(str[i].search(/[a-zA-Z']/)==0){
            tempStr = tempStr + str[i];
        }
        else if(tempStr.length > 0){
            reqArray.push(tempStr);
            tempStr = "";
        }
    }
    return reqArray;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM