Search code examples
javascriptreactjsregex

ReactJS regex doesn't work on a splitted string


So basically I wanted to validate a name from the text first taken from a .txt file and then split. The text looks somewhat like this:

Paris
Museum
1
...

and the code looks like this:

const handleValidation = (data:string) => {
    let pattern = /^[a-zA-Z0-9]{1,10}$/;
    let title = data.split('\n')[0];

    console.log(title);  // returns "Paris" and is a string
    console.log(pattern.test(title));  // returns false
    console.log(pattern.test("Paris"));  // returns true
}

But when instead of title I input "Paris" then it works for some reason, even though they should act the same. Does anyone know what could be the cause of this problem?


Solution

  • The issue you're running into is likely due to hidden characters in the title string when you read it from the file. Even though it looks like "Paris", there might be some extra characters like a carriage return (\r), a trailing space, or something similar that's making the validation fail.

    Here’s why this happens:

    1. When you split the string with split('\n'), it breaks at the newline character, but any extra characters like \r (common in Windows) or spaces may still be attached to title.
    2. So when you check pattern.test(title), it returns false because title isn't exactly "Paris"—it's something like "Paris\r" or "Paris ".

    Quick Fix

    Just trim the title string to remove any unwanted characters:

    const handleValidation = (data: string) => {
        let pattern = /^[a-zA-Z0-9]{1,10}$/;
        let title = data.split('\n')[0].trim();  // .trim() removes extra spaces and characters
    
        console.log(title);  // now this should print exactly "Paris"
        console.log(pattern.test(title));  // and this should return true
    }
    

    By using .trim(), you'll clean up the string and your validation should work as expected!