patternjavascriptMinor
JavaScript replace
Viewed 0 times
javascriptreplacestackoverflow
Problem
I am not sure the square brackets are correct (although it has not yet failed some simple tests). I would also like to reduce and simplify this code to one line if practical. I think the code is self explanatory.
str = str.replace(/[\n]/g,'')
str = str.replace(/[\t]/g,' ')Solution
The square brackets are technically correct, but unneeded:
Also, since a new string is returned, you can chain the methods:
For more information, you can read the MDN pages on replace and regular expressions.
Though the above is one line, if wanted to combine it into one replace, you could, but in my opinion this is uglier and less clear:
This could be useful though if you had a large set of simple replacements:
The idea could be extended farther to automatically generate the regex instead of relying on changing it every time
str = str.replace(/\n/g, "");Also, since a new string is returned, you can chain the methods:
str = str.replace(/\n/g, "").replace(/\t/g, " ");For more information, you can read the MDN pages on replace and regular expressions.
Though the above is one line, if wanted to combine it into one replace, you could, but in my opinion this is uglier and less clear:
str.replace(/(\n|\t)/g, function (s) { return (s === "\n" ? "" : " "); });This could be useful though if you had a large set of simple replacements:
var map = {"\n": "", "\t": " "};
str.replace(/(\n|\t)/g, function (s) { return map[s]; });The idea could be extended farther to automatically generate the regex instead of relying on changing it every time
map is updated.Code Snippets
str = str.replace(/\n/g, "<br>");str = str.replace(/\n/g, "<br>").replace(/\t/g, " ");str.replace(/(\n|\t)/g, function (s) { return (s === "\n" ? "<br>" : " "); });var map = {"\n": "<br>", "\t": " "};
str.replace(/(\n|\t)/g, function (s) { return map[s]; });Context
StackExchange Code Review Q#12454, answer score: 4
Revisions (0)
No revisions yet.