最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - ReplaceAll function in javascript - Stack Overflow

programmeradmin0浏览0评论

I am getting a string "test+test1+asd.txt" and i want to convert it into "test test1 asd.txt"

I am trying to use function str = str.replace("/+/g"," ");

but this is not working

regards, hemant

I am getting a string "test+test1+asd.txt" and i want to convert it into "test test1 asd.txt"

I am trying to use function str = str.replace("/+/g"," ");

but this is not working

regards, hemant

Share Improve this question edited Dec 2, 2009 at 4:37 Crescent Fresh 117k27 gold badges157 silver badges140 bronze badges asked Dec 2, 2009 at 4:29 NewDevNewDev 1091 gold badge1 silver badge5 bronze badges 1
  • 1 Why use a regular expression if it's only one fixed character? – Tim Pietzcker Commented Dec 2, 2009 at 8:39
Add a ment  | 

3 Answers 3

Reset to default 9
str = str.replace(/\+/g," ");

+1 for S.Mark's answer if you're intent on using a regular expression, but for a single character replace you could easily use:

yourString = yourString.split("+").join(" ");

Here is a simple javascript function that replaces all:

function replaceAll (originalstring, exp1, exp2) {
//Replaces every occurrence of exp1 in originalstring with exp2 and returns the new string.

    if (exp1 == "") {
        return;  //Or else there will be an infinite loop because of i = i - 1 (see later).
        }

    var len1 = exp1.length;
    var len2 = exp2.length;
    var res = "";  //This will bee the new string

    for (i = 0; i < originalstring.length; i++) {
        if (originalstring.substr(i, len1) == exp1) {  //exp1 found
            res = res + exp2;  //Append to res exp2 instead of exp1
            i = i + (len1 - 1);  //Skip the characters in originalstring that have been just replaced
        }
        else {//exp1 not found at this location; copy the original character into the new string
            res = res + originalstring.charAt(i);
        }
    }
    return res;
}
发布评论

评论列表(0)

  1. 暂无评论