Read characters from a text string before a space with Javascript

4

I need to do the following, and I can not find a suitable way to do it ...

This is the code of a function, which puts two tabulations (two spaces with \ t) when finding the first space inside the variable 'customText'.

function generatePageLinks(text, isChapter, pageId) {

        //Variable auxiliar que captura el texto de la página de 'text'.

        var aux = text;
        var customText = aux.replace(" ", "\t\t");


        var $element = $(document.createElement('td'));
        var $link = $('<a class="hier-link"></a>').attr('href', '#').attr('data-page-id', pageId).text(customText);

        $element.append('<div class="text-wrapper">');
        $element.append($('<pre class="hier-move">').html(isChapter ? customText : $link));
        return $element;

    }

I need to improve this function, so that it applies two tabulations when there are 2 characters before the space, and a single tabulated in case there are 3 characters before space.

Is it viable? A thousand thanks in advance!

    
asked by djohny 28.06.2016 в 10:48
source

6 answers

4

Use indexOf ... Use to get the first location of the given string.

Example

if (aux.indexOf(' ') == 2) {
  // hay dos caracteres antes del primer espacio 
  var customText = aux.replace(" ", "\t\t"); // se remplaza por 2 tabs
} else if (aux.indexOf(' ') == 3) {
  // hay 3
  var customText = aux.replace(" ", "\t"); // se reeplaza por 1 tab
} else {
   // otro caso
}

Greetings

    
answered by 28.06.2016 / 12:48
source
5

You can use regular expressions:

texto = texto.replace(/([^\s]{2})\s/, "$1\t\t");
texto = texto.replace(/([^\s]{3})\s/, "$1\t");

The first line replaces two characters followed by a space by those two characters followed by two tabs.

The second line replaces three characters followed by a space by those three characters followed by a single tabulator.

Detail of the regular expression

  • [^\s] this means: any character that is not a space
  • [^\s]{2} this means: any character that is not a space, repeated 2 times

If we group something with parentheses, as I did with ([^\s]{2}) , that allows us to use it later when replacing. That is, that match is saved for later use, by means of $1 . If there were several groups, we would use $1 , $2 , $3 , etc.

Visually:

Therefore, going back to the replace, we are looking for 2 characters that are not spaces (we keep them in $1 ), followed by a space, and replace them with $1 followed by two tabs.
And in the second line, instead of 2 characters it's 3, and instead of 2 tabs, it's one.

It can be complicated if you do not know the regular expressions, but in two lines you already have what you were looking for.

The regular expression will always be faster than traversing all the characters and searching by hand. It is also extremely powerful. With just a few changes you can, for example, apply the replacement to the whole text, not just the first appearance, or whatever you can think of.

    
answered by 28.06.2016 в 12:42
2

this is a good occasion to use regular expressions , look for some RegExpr tutorial and play a bit with one of the RegEx test sites such as link

Once you have become familiar with these toys a little, try the following regular expressions against your test chains

this expression ^(\S{2})\s matches when there are exactly two characters at the beginning of the string that are not spaces followed by a blank space and capture the two characters.

this other ^(\S{3})\s does when there are exactly three characters at the beginning of the string that are not spaces followed by a blank space.

Using these regular expressions in javascript to replace the space by tabs is very easy.

Simply use string.replace() with them as the first parameter, and using the text captured in the string.

text.replace(/^(\S{2})\s/, "$1\t\t");

or

text.replace(/^(\S{3})\s/, "$1\t");
    
answered by 28.06.2016 в 13:04
0

You can use javascript like this:

var str="Hello world!"; var res = str.substr (0, 2);

Result

He

Or you can do this too:

var str = "Hello world!";
var res = str.split(" ");

Result

res[0] = Hello
res[1] = world!

I hope it serves you

    
answered by 28.06.2016 в 10:52
0

Depending on how you pose, I do not know if you just want to replace the first appearance of the spaces or all the times they appear.

If it is only the first one, it would be advisable to do a search with indexOf.

However, I think you mean replacing all triple spaces with a tabulator, and double ones with 2 tabs. In that case the correct thing would be:

var customText = text.replace(/^[ ]{3}/, "\t")
                     .replace(/^[ ]{2}/, "\t\t");

First: the brackets are not strictly necessary, but I put them to make it explicitly clear that normal blanks are being replaced. It is not correct to use the "\ s" since this operator also takes into account tabulators and line breaks.

Second: The 3 spaces are performed first, since the case of 2 is similar but smaller and this can affect the other.

"   " cambiaría por "\t\t " y ya el cambio de 3 no tendría efecto.
    
answered by 28.06.2016 в 14:53
0

In the following example I show the correct way to do it, for this you must use the expression /\s+/ to solve the problem since a tab counts as space per such a reason could be the case where:

  • there is a space or tab and it must be replaced by 2 tabs (in the case where there are 2 characters at the beginning) .

  • there is 2 space or tabs and they must be replaced by 1 tab (in the case where there are 3 characters at the beginning ( that is why I consider placing the + sign in the expression, starting from the case where we must count the first space and all those that follow it to obtain the desired result).

  • In the following example I show the cases raised together with the different expressions given in other answers of this question:

    var exp = [ /[ ]/, /\s/, /\s+/ ];
    for (i in exp) {
     console.log("aplicando exp["+exp[i]+"]:"); 
     console.log("En texto con 1 espacio"); 
     console.log(addTabs(exp[i], "ab cdef"));
     console.log(addTabs(exp[i], "abc def"));
     console.log("En texto con 2 espacio"); 
     console.log(addTabs(exp[i], "ab  cdef"));
     console.log(addTabs(exp[i], "abc  def"));
     console.log("En texto con espacios+tab"); 
     console.log(addTabs(exp[i], "ab \t cdef"));
     console.log(addTabs(exp[i], "abc \t def"));
    }
    
    function addTabs(exp, text) {
     text = text.replace(exp, function (str, i, text) {
      if(i == 2){
       return "\t\t";
      } else if(i == 3){
       return "\t";
      } else {
       return str;
      }
     });
     return text;
    };

    As you will see where we apply the expression / \ s + / the 3 examples give the same result, however you draw your own conclusions of what the correct way should be, Greetings !! ;)) ...

        
    answered by 19.05.2017 в 17:38