javascript - Ignore string whitespace

Asked

Viewed 528 times

0

I have this function in javascript and need to ignore the whitespace of the string. I think the function is removing the "Blank Spaces". Does anyone know how I use this same function without removing the blanks?

function getParameterByName(name) {
    if (name !== "" && name !== null && name != undefined) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace("/\+/g", " "));
    } else {
        var arr = location.href.split("/");
        return arr[arr.length - 1];
    }

}
  • I didn’t understand anything, you say first "I need you to ignore the whitespace" and then "without removing the whitespace". You could explain better what you want by providing an example of input and output of the desired result?

  • Hello Guilherme, 13dev solved the function. I have the string "TABLE TENNIS" which had a null result. Now with the new function it brings with the blanks. Thanks!

  • Although solved, was very confused the question. Blank Spaces and blanks are the same thing. rs

  • 1

    I found nothing confusing, the function has to ignore the presence of white spaces, that is, turn your back on them :)

1 answer

1


When the name parameter exists these return the following:

return results === null ? "" : decodeURIComponent(results[1].replace("/\+/g", " "));

Then that line is to compare the result if it is not null will go through the function decodeURIComponent() and you’re passing as argument results[1].replace("/\+/g", " " same as removing whitespace

you can simply replace with results[1] and your problem will be solved

function getParameterByName(name) {
    if (name !== "" && name !== null && name != undefined) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : results[1];
    } else {
        var arr = location.href.split("/");
        return arr[arr.length - 1];
    }
}
  • Hello 13dev, all right? That’s what I wanted to do, your code is correct, the function included the whitespace. Thanks man!!

  • if it helped you mark the answer, you’re welcome!

  • All that was left was an explanation of what you did in code 13dev! You have to show the link to understand what it is to mark the answer as it accepts https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

  • @Leocaracciolo edited

  • 1

    +1 for the clarification

Browser other questions tagged

You are not signed in. Login or sign up in order to post.