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

Replace function of JavaScript don't work - Stack Overflow

programmeradmin2浏览0评论

I have next code in javascript:

csvReport.name = "My New Report";
$scope.filename = csvReport.name.replace(" ", "_");

But I get $scope.filename = My_New Report. Not all spaces replacing.

What is it?

I have next code in javascript:

csvReport.name = "My New Report";
$scope.filename = csvReport.name.replace(" ", "_");

But I get $scope.filename = My_New Report. Not all spaces replacing.

What is it?

Share Improve this question edited Oct 25, 2013 at 12:20 crashmstr 28.6k9 gold badges64 silver badges80 bronze badges asked Oct 25, 2013 at 12:18 IFrizyIFrizy 1,7454 gold badges18 silver badges33 bronze badges 2
  • Why did you tag this performance? – crashmstr Commented Oct 25, 2013 at 12:19
  • all answers below are correct, yet none of the authors care to upvote the other correct ones... that's a bit of a disappointment :( – Zathrus Writer Commented Oct 25, 2013 at 12:24
Add a ment  | 

4 Answers 4

Reset to default 5

.replace will always replace the first occurence except if you use regular expression like that :

csvReport.name.replace(/ /g, "_");

You can use replace with a regular expression :

"My New Report".replace(/ /g,'_')

Demo

You can use regular expression with a global switch (g) to actually replace all instances, like this:

csvReport.name = "My New Report";
$scope.filename = csvReport.name.replace(/ /g, "_");

Function replace only replace first appearance of first argument. You can use regular expression to replace in whole string.

Try this:

if (!String.replaceAll) {
    String.prototype.replaceAll = function(replace, value) {
        var regexpStr = replace.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
        return this.replace(new RegExp(regExpStr, 'g'), value);
    };
}

This way you have additional function that works on whole string.

发布评论

评论列表(0)

  1. 暂无评论