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

Replacing carets in Javascript - Stack Overflow

programmeradmin4浏览0评论

I'm trying to replace multiple carets (^) in a string with spaces in Javascript. Following the w3schools entry on replace(), I used this code:

var str = "Salt^Lake^City, UT";
var result = str.replace(/^/g, " ");

However, value of result is " Salt^Lake^City, UT". One caret is replaced when I run this code:

var result = str.replace("^", " ");

but I want to replace all of an arbitrary number of carets. Is there something obvious I'm missing about globally replacing in Javascript? I could write a function using str.replace("^", " "); to remove all the carets, but I'd rather use the built-in global replace.

I'm trying to replace multiple carets (^) in a string with spaces in Javascript. Following the w3schools entry on replace(), I used this code:

var str = "Salt^Lake^City, UT";
var result = str.replace(/^/g, " ");

However, value of result is " Salt^Lake^City, UT". One caret is replaced when I run this code:

var result = str.replace("^", " ");

but I want to replace all of an arbitrary number of carets. Is there something obvious I'm missing about globally replacing in Javascript? I could write a function using str.replace("^", " "); to remove all the carets, but I'd rather use the built-in global replace.

Share Improve this question asked Mar 13, 2013 at 17:51 lk135lk135 1,3692 gold badges13 silver badges17 bronze badges 1
  • Don't consult w3schools. Some information on that webpage is wrong (see this for an explanation: w3fools.) – Max Leske Commented Mar 13, 2013 at 17:55
Add a ment  | 

2 Answers 2

Reset to default 8

The ^ character matches the start of the string in a regex, so you need to escape it so it will be treated as a literal character. That is why in your example, the result string has a new space added at the start of the string.

var result = str.replace(/\^/g, " ");

You can also use another handy way which is roundabout.

var result = str.split('^').join(' ') ;
发布评论

评论列表(0)

  1. 暂无评论