I am trying to write a function where the parameter is a string and a specific character needs to be replaced. It will then give an alert box with the converted string.
I have the following code but it isn't working. I also want it to alert()
the converted string.
function encryption(aString){
return aString.replace(/a/g, '@')
.replace(/e/g, '()')
.replace(/h/g, '#')
.replace(/l/g,'1')
.replace(/r/g,'+')
.replace(/s/g.'$')
.replace(/v/g,'^')
.replace(/x/g,'*');
}
At first sight I see a typo here
.replace(/s/g.'$')
It should be
.replace(/s/g,'$')
You can see it working here after fixing the typo
There are two problems here:
.replace(/s/g.'$')
The period should be a comma, and the $
character is used for replacements code in the replacement string, so you have to escape it as $$
:
.replace(/s/g, '$$')
You can use a single replace instead of chaining all those replaces:
function encryption(aString){ return aString.replace(/[aehlrsvx]/g, function (m) { return m == 'e' ? '()' : '@#1+$^*'['ahlrsvx'.indexOf(m)]; }); } // display result in StackOverflow snippet document.write(encryption('The quick brown fox jumps over the lazy brown dog.'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.