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

javascript - String replace from JSON - Stack Overflow

programmeradmin4浏览0评论

I have a JSON response that is not properly formatted and has speical characters ing in and I want to clean it up by removing the special characters using string.replace(). For some reason it is not working.

Here is the JSON result

[{"User::newPassword":["Password could not be changed. The request can't be validated"]},[]]

and here is my expression.

resp.replace(::g, '');

But it doesn't seem to work. Any advice on this would be appreciated as there is nothing I can do for it on the backend.

I have a JSON response that is not properly formatted and has speical characters ing in and I want to clean it up by removing the special characters using string.replace(). For some reason it is not working.

Here is the JSON result

[{"User::newPassword":["Password could not be changed. The request can't be validated"]},[]]

and here is my expression.

resp.replace(::g, '');

But it doesn't seem to work. Any advice on this would be appreciated as there is nothing I can do for it on the backend.

Share Improve this question edited Aug 31, 2015 at 4:18 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Aug 31, 2015 at 3:31 Bazinga777Bazinga777 5,30113 gold badges56 silver badges95 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

You cannot use replace() on JSON.

If you're working with strings

:: should be in quotes if you want to replace first occurrence of it.

resp.replace('::', '');

If you want to replace all occurrences, use / as delimiter of regex.

resp.replace(/::/g, '');

If you're working with JSON

  1. Convert the JSON to string using JSON.stringify()
  2. Use replace on string
  3. Convert string back to JSON using JSON.parse()

Using Object methods

You can also change the key to remove :: from it

var newKey = key.replace('::', ''); // Create new key by replacing the `::`
obj[newKey] = obj[key]; // Add new key and value in object
delete key; // Remove old key
发布评论

评论列表(0)

  1. 暂无评论