skip to Main Content

How can I test whether a string contain 1 or more than one dot put together. Please show me where I went wrong in the code below.

<!DOCTYPE html>
<html>
<body>



<p id="demo"></p>

<script>
let text = "Is this .. all there is?";
let pattern = /[^.+]/g;// not allow more than one dot put tothether 
//should return false but instead return true
let result = pattern.test(text)

document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>

3

Answers


  1. Use this regex /.{2,}/g

    Quantifier {} represents the length two or more and you can only set string as inner HTML content not boolean like true or false directly.

    let text = "Is this .. all there is?";
    let text2 = "Is this . all there is?";
    let pattern =/.{2,}/g;// use this regex
    let result = pattern.test(text);
    let result2 = pattern.test(text2);
    
    document.getElementById("demo").innerHTML = `${text}'s result: ${result?"true":"false"}`;
    
    document.getElementById("demo2").innerHTML = `${text2}'s result: ${result2?"true":"false"}`;
    <!DOCTYPE html>
    <html>
    <body>
    
    <p id="demo"></p>
    <p id="demo2"></p>
    
    </body>
    </html>
    Login or Signup to reply.
  2. "… How can I test whether a string contain 1 or more than one dot put together. …"

    Use the ^ and $ sytnax, signifying the start and end of line.

    var s = 'abc ... 123'
    console.log(/^[^.]+$/g.test(s))
    Login or Signup to reply.
  3. Your regular is not right for your purpose. It matches a single character not present in the list: [^.+] (. or + character), then it will always return true if the string contains any character that is not . or +.

    You could check if string contains more than one dot put together, using this pattern: /..+/g

    <!DOCTYPE html>
    <html>
    <body>
    
    
    
    <p id="demo"></p>
    
    <script>
    let text = "Is this .. all there is?";
    let pattern = /..+/g;// check if there is more than one dot put together 
    //should return true
    let result = pattern.test(text)
    
    document.getElementById("demo").innerHTML = result;
    </script>
    
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search