-2

Sorry for my poor english.

During creating my private portfolio website, I found

    textTest1();
    textTest2();
    function textTest1(){
    var pText1 = $('p.textTest1').text();
    var newString ='';
    for(var i=0;i<pText1.length;i++){
        console.log('total index of text1 is'+ i);
    }
}
function textTest2(){
    var pText2 = $('p.textTest2').text();
    var newString2 ='';
    for(var i=0; i<pText2.length;i++){
        console.log('total index of text2 is' + i);
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="textTest1">text test</p>   
        <p class="textTest2">
            text 
            test
        </p>

these two p tags have different length. I understand why it happens

because I had similar problem with CSS.

No problem if text is small, but it would be annoying if text takes more

than two~three lines.

Writing all texts in one line can solve problem but if the text is very long and

there are some tags inside(example: span, i) it will be horrible to read

and find in text editor.

Does somebody have any idea to solve or avoid problem such like this? (I mean

to get a real and right length of text)

oehqoehfo
  • 65
  • 1
  • 8
  • Duplicate with https://stackoverflow.com/questions/360491/how-do-i-strip-white-space-when-grabbing-text-with-jquery – emil Jan 19 '18 at 23:57
  • @emil thank you for a great link. I didn't really expect replace method should fix the problem. That's why I posted the question. Heh.. means I should learn more and more. Thank you for a great link! – oehqoehfo Jan 20 '18 at 00:08
  • @FrankerZ Sorry. I forgot accepting.. – oehqoehfo Jan 20 '18 at 00:19
  • Ignore the down voters, they bust have born expert programmers, the rest of us learn from asking questions when we are stuck. – SANM2009 Jan 20 '18 at 02:19

4 Answers4

1

The main issue is the whitespace (The spaces and new lines). We can see this by doing this:

var pText1 = $('p.textTest1').text();
var pText2 = $('p.textTest2').text();

console.log('"' + pText1 + '"', pText1.length);
console.log('"' + pText2 + '"', pText2.length);

//To fix this, one solution could be to strip all non-alphanumeric characters:

pText1 = pText1.replace(/\W+/g, '');
pText2 = pText2.replace(/\W+/g, '');

console.log('"' + pText1 + '"', pText1.length);
console.log('"' + pText2 + '"', pText2.length);

//Even better, let's create a function that just handles excess whitespace.

function cleanText(str) {
  //Trim all whitespace at the start and end
  str = str.trim();
  //Replace all whitespace (new lines, excess spaces) with just one space
  str = str.replace(/\s+/g, ' ');
  
  return str;
}

console.log('cleanText():');

pText1 = cleanText($('p.textTest1').text());
pText2 = cleanText($('p.textTest2').text());

console.log('"' + pText1 + '"', pText1.length);
console.log('"' + pText2 + '"', pText2.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="textTest1">text test</p>   
        <p class="textTest2">
            text 
            test
        </p>

Each space, tab, and new line counts as 1 character for .length calculations.

Blue
  • 22,608
  • 7
  • 62
  • 92
1
  • First, call .trim() to remove the leading and trailing spaces.
  • Then call .replace() to remove the space, new lines and carriage returns in between words with a single space.

Also, you don't need to loop over the string to get its length, just use the .length property:

function getTrueLength(str){
  // Trim off the leading and trailing spaces, then replace the space, 
  // returns and new lines in the middle with a single space
  return str.text().trim().replace(/(\s+|\r+|\n+)/, " ").length;
}

console.log('total index of text1 is ' + getTrueLength($('p.textTest1')));
console.log('total index of text2 is ' + getTrueLength($('p.textTest2')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="textTest1">text



test</p>   
<p class="textTest2">
            text 
            test
</p>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

Use regular expression to remove new line and tab.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
    <p class="textTest1">text test</p>   
    <p class="textTest2">
        text 
        test
    </p>
    <script>
        textTest1();
        textTest2();

        function textTest1(){
            var pText1 = $('p.textTest1').text();
            var newString ='';
            for(var i=0;i<pText1.length;i++){
                console.log('total index of text1 is'+ i);
            }
        }
        function textTest2(){
            var pText2 = $('p.textTest2').text()
                            .replace(/\n/g, '')
                            .replace(/\t/g, ''); // and any other replace you want

            console.log(pText2);
            var newString2 ='';
            for(var i=0; i<pText2.length;i++){
                console.log('total index of text2 is' + i);
            }
        }
    </script>
</body></html>
Andam
  • 2,087
  • 1
  • 8
  • 21
0

Use:

pText1.match(/[^\s]+/g).join(' ');

This will match anything except spaces, put them into array and then join them by only one space. working example bellow:

textTest1();
textTest2();

function textTest1(){
    var pText1 = $('p.textTest1').text();
    
    console.log(pText1.match(/[^\s]+/g).join(' ').length);
    console.log(pText1.match(/[^\s]+/g).join(' '));
}

function textTest2(){
    var pText2 = $('p.textTest2').text();
    
    console.log(pText2.match(/[^\s]+/g).join(' ').length);
    console.log(pText2.match(/[^\s]+/g).join(' '));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="textTest1">text test</p>   
<p class="textTest2">
            text 
            test
</p>
YouneL
  • 8,152
  • 2
  • 28
  • 50
  • 1
    Remove the `+` from the character set. It's interpreted as an actual `+` character and so it's excluded. `pText1.match(/[^\s]+/g)` You could also make it shorter with `\S` instead. `pText1.match(/\S+/g)` –  Jan 20 '18 at 01:12