Reputation: 61
I've got a problem, I am trying to use a replace function in JavaScript and I cannot get it to work. I'm using:
var pagename = projectname.replace (" ", "");
But it only takes the first space, I wanted to take all the spaces. example:
"My first project 1" = "Myfirstproject1", ie get everything together.
I'm developing the script of google apps.
Thank you.
Upvotes: 3
Views: 23126
Reputation: 419
Unfortunately, replaceAll
is not available in Google AppScript.
You may use RegExp
version of replace
to implement replaceAll
.
If you want to create some kind of generic solution, you need to escape subject from special RegExp
characters, as symbols like .^
(and many others) have special meaning in regular expressions.
function strReplaceAll(subject, search, replacement) {
function escapeRegExp(str) { return str.toString().replace(/[^A-Za-z0-9_]/g, '\\$&'); }
search = search instanceof RegExp ? search : new RegExp(escapeRegExp(search), 'g');
return subject.replace(search, replacement);
}
We may also add this to string class, but I suggest to test if is already here, just in case it may be added in later versions of Google AppScript.
if (String.prototype['replaceAll'] == null) {
String.prototype['replaceAll'] = function(search, replacement) {
return strReplaceAll(this, search, replacement)
};
}
Also, please pay attention, that $
has special meaning in replacement string in replaceAll
(JavaScript also work this way). So probably you need additional function escapeReplacementString
to handle this in case pure text-to-text replace (this function is also useful in JavaScript).
function escapeReplacementString(str) { return str.toString().replace(/\$/g, '$$$&'); }
So generic text-to-text replace will be like text.replaceAll(search, escapeReplacementString(replace))
:
var text = 'Money is +'; search = '+'; replace = '$& and $$';
console.log(text.replaceAll(search, replace)); // gives you 'Money is + and $' [?!]
console.log(text.replaceAll(search, escapeReplacementString(replace))); // gives 'Money is $& and $$'
More: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
JSFiggle playground: https://jsfiddle.net/r8geycLq/
Upvotes: 1
Reputation: 373
You use this code outside other function.
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
Then you can use replaceAll function. Example :
var text = "H e l l o W o r l d";
text = text.replaceAll(" " , "");
Result : HelloWorld
Upvotes: 9
Reputation: 3774
You should try :
var pagename = projectname.replace (/\s/g, '');
the g
at the end of the regular expression, is a flag indicating to the replace method that it shouldn't replace only the first occurrence of the space character.
Upvotes: 18