Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

javascript - Capitalize the first letter of first word inside the brackets

I want to capitalize the first letter of each string inside the brackets...

If we have this string:

const text = 'This [forest or jungle] is [really] beautiful';

The desired result would be 'This [Forest or jungle] is [Really] beautiful'

So far:

I have the capitalize function:

function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
} 

And here we have this regex code to select string inside the brackets:

/(?<=[)(.*?)(?=])/g

Please help

question from:https://stackoverflow.com/questions/65835371/capitalize-the-first-letter-of-first-word-inside-the-brackets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use

text = text.replace(/(?<=[)[a-z](?=[^][]*])/g, (x) => x.toLocaleUpperCase())
// OR
text = text.replace(/(?<=[)p{Ll}(?=[^][]*])/gu, (x) => x.toLocaleUpperCase())

See the regex demo/regex demo #2. Details:

  • (?<=[) - a positive lookbehind that matches a location that is immediately preceded with a [ char
  • [a-z] - a lowercase ASCII letter
  • p{Ll} - any Unicode lowercase letter
  • (?=[^][]*]) - a positive lookahead that requires any zero or more chars other than [ and ] and then a ] immediately to the right of the current location.

See the JavaScript demo:

const text = 'This [forest or jungle] is [really] beautiful';
console.log( text.replace(/(?<=[)[a-z](?=[^][]*])/g, (x) => x.toLocaleUpperCase()) )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...