如何使用JavaScript从字符串中删除特殊字符

时间:2019-02-06 05:42:20

标签: javascript

当#以字符串形式出现时,我想使用JavaScript在新行中将其分割。

请帮助我。

样本输入:

.{0,300}

预期输出:

This application helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#

4 个答案:

答案 0 :(得分:1)

您可以通过replace通过'#' '\n'

var mainVar = 'This application helps the user to instantiate#Removed#Basic#afdaf#Clip#Python#matching';
console.log(mainVar.replace(/[^\w\s]/gi, '\n'));

答案 1 :(得分:1)

将字符串转换为数组,并在数组中循环并逐个打印值。

var str = "helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#";

    str.split("#").forEach(function(entry) {
        console.log(entry);
    });

答案 2 :(得分:0)

您可以尝试以下方法:

您应该在单个正则表达式中使用字符串替换功能。假设有特殊字符

var str = "This application helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#";
console.log(str.replace(/[^a-zA-Z ]/g, "\n"));

答案 3 :(得分:0)

以下解决方案将基于#拆分并将其存储在数组中。 此解决方案可用于拆分字符串。

var sentence = '#Removed#Basic#afdaf#Clip#Python#matching of many parts#'

var newSentence = [];
for(var char of sentence.split("#")){
    console.log(char); // This will print each string on a new line
    newSentence.push(char);
}
console.log(newSentence.join(" "));