Home > Software engineering >  Calculate the string length of only characters (not symbols) in the string using Javascript
Calculate the string length of only characters (not symbols) in the string using Javascript

Time:05-21

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.

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.

CodePudding user response:

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 (/* [...] */) {
        // [...]
    }
}
  • Related