简体   繁体   中英

Doubts in JavaScript RegExp and String.replace() method

I am trying to enter 'username' in a webpage using VBA. So in the source code of the webpage, there are some modifications done to the 'username' value.

I have attached the code,

function myFunction()        
   {
    document.str.value = "Abc02023";
    document.str.value  = document.str.value.toUpperCase();
    pattern = new RegExp("\\*", "g");
    document.str.value = document.str.value.replace(pattern, "");
    document.str.value = document.str.value.replace(/^\s+/, "");
    document.str.value = document.str.value.replace(/\s+$/, "");
   }

I read about these and from my understanding, after the modifications document.str.value is ABC02023 . Obviously I am wrong as there would not be no point in doing all these modifications then. Also, I am getting an 'incorrect username error'.

So can anybody please help me to understand these. What would be the value of document.str.value and how did you figure it out? I am new to JavaScript so please forgive me if I am being too slow...

Looks like you are using some very old code to learn from. ☹ Let's see if we can still learn something by bringing this code up to date, then you go find some newer learning materials. Here is a well-written book series with free online versions available: You Don't Know JS .

function myFunction() {

    // Assuming your code runs in a browser, `document` is equal to the
    // global object. So if in a browser and somewhere outside the function
    // a variable `str` has been created, this will add an attribute `value`
    // to `str` and set the value of `str.value` to 'Abc02023'. If there is 
    // no already existing object `document` (for instance not running in 
    // a browser) or if document does not have an already created property
    // called`str` then this will throw a TypeError because you cannot add 
    // a property to `undefined`.

    document.str.value = "Abc02023";

    // You probably were just trying to create a new variable `str` so let's
    // just start over
}

Second try

function myFunction() {
    // create a variable `str` and set it to 'Abc02023'

    var str = "Abc02023";

    // Take value of str and convert it to all capital letters
    //   then overwrite current value of str with the result.
    //   So now `str === 'ABC02023'

    str  = str.toUpperCase();

    // Create a regular expression representing all occurences of `*`
    //   and assign it to variable `pattern`.

    var pattern = new RegExp("\\*", "g");

    // Remove all instances of our pattern from the string. (which does not
    // affect this string, but prevents user inputting some types of bad
    // strings to hack your website.

    str = str.replace(pattern, "");

    // Remove any leading whitespace form our string (which does not
    //  affect this string, but cleans up strings input by a user).

    str = str.replace(/^\s+/, "");

    // Remove any trailing whitespace form our string (which does not
    //  affect this string, but cleans up strings input by a user).

    str = str.replace(/\s+$/, "");

    // Let's at least see our result behind the scenes. Press F12 
    //  to see the developer console in most browsers.

    console.log("`str` is equal to: ", str );
}

Third try, let's clean this up a little:

// The reason to use functions is so we can contain the logic 
//  separate from the data. Let's pull extract our data (the string value)
//  and then pass it in as a function parameter

var result = myFunction('Abc02023')
console.log('result = ', result)

function myFunction(str) {

    str  = str.toUpperCase();

   // Nicer syntax for defining regular expression.

    var pattern = /\*/g;

    str = str.replace(pattern, '');

    //  Unnecesarry use of regular expressions. Let's use trim instead
    //   to clean leading and trailing whitespace at once.

    str = str.trim()

    // let's return our result so the rest of the program can use it

    // return str
}

Last go round. We can make this much shorter and easier to read by chaining together all the modifications to str . And let's also give our function a useful name and try it out against a bad string.

var cleanString1 = toCleanedCaps('Abc02023')
var cleanString2 = toCleanedCaps(' ** test * ')

console.log('cleanString1 = ', cleanString1)
console.log('cleanString2 = ', cleanString2)

function toCleanedCaps(str) {
    return str
        .toUpperCase()
        .replace(/\\*/g, '')
        .trim()
}

@skylize answer is close

what is equivalent to your code is actually

function toCleanedCaps(str) {
    return str
        .toUpperCase()
        .replace(/\*/g, '') // he got this wrong
        .trim()
}

Let's go over the statements one by one

document.str.value  = document.str.value.toUpperCase();

makes the string uppercase

pattern = new RegExp("\\*", "g");
document.str.value = document.str.value.replace(pattern, "");

replaces between zero and unlimited occurences of the \\ character , so no match in this case.

document.str.value = document.str.value.replace(/^\s+/, "");

replaces any whitespace character occurring between one and unlimited times at the beginning of the string, so no match.

document.str.value = document.str.value.replace(/\s+$/, "");

replaces any whitespace character occurring between one and unlimited times at the end of the string, so no match.

You are right. With "Abc02023" as input, the output is what you suggest.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM