Javascript replacement of the characters *, +, and / within a string

13,011

Solution 1

Is there a reason not simply to escape the *, +, and / characters with backslashes in the regex?

s = s.replace( /\*/g, 'star' );

Solution 2

To me, chaining replaces isn't very elegant. I would try:

var symbols = {
    '@': '%40',
    '&': '%26',
    '*': '%2A',
    '+': '%2B',
    '/': '%2F',
    '<': '%3C',
    '>': '%3E'
};
str = str.replace(/([@*+/]|&(amp|lt|gt);)/g, function (m) { return symbols[m]; });

Conveniently, this also avoids the original problem.

Share:
13,011
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin over 1 year

    Alright, so I'm currently working on a simplistic manner of mimicking the function of PHP's urlencode() with JS's escape() and some string replacement. I'm purely looking at keyboard characters, so no special ASCII or Unicode characters. The problem I'm encountering is that the specific characters *, +, and / all have special meanings in RegExp, and seeing as JavaScript String Object methods use RegExp parameters, I cannot fully replicate PHP's urlencode(). Thus, how would one manage to perform a replacement of these characters within a string using JS?

    Background information:
    escape() discrepancies with urlencode():
    @: not converted, should be %40
    &: considered an html entity, thus is escaped as %26amp%3B rather than %26
    *: not converted, should be %2A
    +: not converted, should be %2B
    /: not converted, should be %2F
    <: considered an html entity, thus is escaped as %26lt%3B rather than %3C
    >: considered an html entity, thus is escaped as %26gt%3B rather than %3E

    HTML Entity conversion is as simple as

    str.replace(/&amp;/g, '%26').replace(/&lt;/g, '%3C').replace(/&gt;/g, '%3E');
    

    and @ can be replaced, as it is not a reserved RegExp character.
    * represents the {0} conditional
    + represents the {1} conditional
    / is the basic RegExp tag character

    Thank you for your time.

  • Robusto
    Robusto about 13 years
    It contains an asterisk, not an asterix.