Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate the string length of only characters (not symbols) in the string using Javascript

I am trying to select words being passed through an IF statement based on only their character length, ignoring symbols.

For example If I have the word "hello!" I want the if statement to recognise it as a length of 5 characters.

I want to keep the symbol in the word when it is then added to updatedString. I just don’t want to count the symbol in the original count. I have spent a while considering regex options but am struggling to find something that would work in this particular case.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

An example of part of the code is below. (updatedString is declared outside of the if-loop)

 for (let word in arr) {
   if (arr[word].length == 5 || arr[word].length == 6) {
      let bold = arr[word].slice(0, 3)
      let normal = arr[word].slice(3)
      updatedString += `<b>${bold}</b>${normal} ` 
    }
   else if {
   ...
  }
 }

What I ultimately want is the area "arr[word].length == 5" to only count characters.

For the sake of this program I will assume that all words input in via the user will be those used in normal news or academic articles and nothing too obscure.

Any advice would be greatly appreciated, thanks.

>Solution :

You can use regex like so:

text = "hello!"
text.match(/[a-z]/g).join("") // join to return a string without any symbols

If you need to match more characters just update the pattern.

In your particular case it would look something like this:

for (let word in arr) {
    if (arr[word].match(/[a-z]/g).length == 5 || arr[word].match(/[a-z]/g).length == 6) {
        let bold = arr[word].slice(0, 3)
        let normal = arr[word].slice(3)
        updatedString += `<b>${bold}</b>${normal} ` 
    }else if (/* [...] */) {
        // [...]
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading