skip to Main Content

i’m trying to add spaces between the words which is coming from the json in the frontend ,but im unable to do that is there any way to do it
here is my code .

 const toSentenceCase = (str: string) => {
    return str.charAt(0).toUpperCase() + '' + str.slice(1).toLowerCase()
  }
  return (
      <div className='fv-row mb-10'>
        <label className='form-label fs-6 fw-bolder text-dark d-flex'>Intent type</label>
        <Form.Select
          aria-label='Select htmlInputTypes'
          className='form-control form-control-lg form-control-solid'
          value={newIntentType}
          onChange={handleTypeChange}
        >
          {defaultJson.map((item, index) => (
            <>
              <option value='' disabled selected hidden>
                Select a Intent Type
              </option>
              <option key={index} value={item.type}>
                {toSentenceCase(item.type)}
              </option>
            </>
          ))}
        </Form.Select>
      </div>

and here is my json

  {
    "type": "textWithImage",
    "intent": {
      "id": null,
      "message": "Hi!",
      "trigger": 1,
      "metadata": {
        "payload": [
          {
            "url": "",
            "type": "null",
            "caption": "null"
          }
        ]
      },
      "userInput": false
    }
  },

The result which is coming:
Textwithimage

Expected result:
Text with image

i want this Text with image result but constantly im getting the wrong , i dont want the text to be camelCase but to be displayed in the sentance case is there any approch to handle it plese tell me.

2

Answers


  1. Find all uppercase characters following a lowercase character and replace them with a space inserted:

    input.replaceAll(/([a-z])([A-Z])/, '$1 $2');
    

    You can then use your function to capitalize the whole string.

    You can also pass a replacer function to transform to lower case in one go:

    input.replaceAll(
      /([a-z])([A-Z])/,
      (match, p1, p2) => `${p1} ${p2.toLowerCase()}`);
    

    Note that neither of the two methods will handle digits, umlauts or characters outside of the a-z ASCII range.

    Login or Signup to reply.
  2. You need to insert a space before every uppercase letter that is preceded by a lowercase letter in your string and then lowercase it. For example:

    const toSentenceCase = (str) => {
      return str.charAt(0).toUpperCase() +
             str.slice(1).replace(/(?<=[a-z])([A-Z])/g, ' $1').toLowerCase()
    }
    
    console.log(toSentenceCase('textWithImage'))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search