DEV Community

sifatul
sifatul

Posted on

10 string methods you must know as a js beginner

Naming conventions are most commonly used. Good to remember these terms.

1.UPPERCASE

"hello world".toUpperCase()
Enter fullscreen mode Exit fullscreen mode

2.lowercase

"hello world".toLowerCase()
Enter fullscreen mode Exit fullscreen mode

3.camelCase

"hello world"
.replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) => {
 if(index === 0) return word.toLowerCase()
 return word.toUpperCase();
})
.replace(/\s+/g, "");
Enter fullscreen mode Exit fullscreen mode

4.PascalCase

"hello world"
 .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => {
  return word.toUpperCase();
 })
.replace(/\s+/g, "");
Enter fullscreen mode Exit fullscreen mode

Few more that are commonly used with forms.

5.is a valid url

/^(ftp|http|https):\/\/[^ "]+$/.test("https://leetcode.com/");
Enter fullscreen mode Exit fullscreen mode

6.get list of query strings from url

const url = "https://www.google.com/doodles/maurice-sendaks-85th-birthday?hl=en-GB"
const params = (url.split('?')?.[1]?.split('&') || [])
 .reduce((prev, current) => {
  const keyVal = current.split('=');
  const key = keyVal[0];
  const val = keyVal[1];
  prev[key] = val;
  return prev;
 }, {});
Enter fullscreen mode Exit fullscreen mode

7.remove special string from a text

"hello@world".replace(/[^\w\s]/gi, '')
Enter fullscreen mode Exit fullscreen mode

8.get ascii value of a character

'a'.charCodeAt(0)
Enter fullscreen mode Exit fullscreen mode

9.convert json to string

const obj = {
 key:'value'
}
JSON.stringify(obj)
Enter fullscreen mode Exit fullscreen mode

10.convert object string to json

JSON.parse('{"key":"value"}')
Enter fullscreen mode Exit fullscreen mode

You can get all these and many more commonly used functions in a single npm package but as a beginner it's good to know how these are done.

I will be posting bi-weekly for javascript developers. Feel free to request for topics that you would like to learn or recommend in the comment section.

Top comments (0)