Javascript string code function

Built-in String functions in JavaScript

A detailed review of useful JS functions that will help you work with the String data type.

Introduction

In JavaScript, all text data is a String . It doesn’t matter if there’s 1 char or 10k lines, it’s still a String . Before we get to the review of the built-in String functions, take a note that the length of all JS strings is stored in the length property. You can access it directly and don’t have to call any specific getter method.

const s = 'Hello, World!'; console.log(s.length); 

The second important point, that deserves its own quote is

All strings in JS are immutable.

Once a string is created, it will never be changed. Functions like replace or slice , will always return a new string, but the original one will be left intact.

For demonstration purposes I’ll assume we have some string s declared as a constant with the value I am going to become a FULL STACK JS Dev with Coderslang . Further, I’ll list some ideas that we might want to apply to this string and ways to do this.

const s = 'I am going to become a FULL STACK JS Dev with Coderslang'; 

How to check if a string includes another string

To check if our string contains another string, we should use the includes function. It will return true or false based on the result of the check.

console.log(s.includes('FULL STACK')); // true console.log(s.includes('cheeseburger')); // false 

Another way of doing this is by using the indexOf or lastIndexOf functions. Both of them will lookup if the string contains another string and returns the index of the beginning of the match. If no match is found, it means that the original string doesn’t include the search string and the result will be -1;

console.log(s.indexOf('AWS')); // -1 console.log(s.lastIndexOf('AWS')); // -1 

The difference between indexOf and lastIndexOf becomes evident when there are multiple matches inside the string.

console.log(s.indexOf('g')); // 5 console.log(s.lastIndexOf('g')); // 55 
  • indexOf starts the lookup from the beginning
  • lastIndexOf starts the lookup from the end

This determines the difference in the result.

In any case, we can use both indexOf and lastIndexOf functions to determine if one string includes another one in JavaScript. If the result is anything other than -1 , then it does. Otherwise, it doesn’t.

How to determine if one string starts with another string

To check if a string starts with another string, there’s a startsWith function. It returns true if our string starts with another string or false if it doesn’t.

console.log(s.startsWith('I am')); // true console.log(s.startsWith('You are')); // false 

How to determine if one string ends with another string

To check if a string ends with another string, there’s an endsWith function. It works almost the same way as startsWith , but it checks the end of the string, not the start.

console.log(s.endsWith('Coderslang')); // true console.log(s.endsWith('Node.js')); // false 

How to remove spaces at the beginning of the end of the string

To remove the whitespace at the start or the end of the string, you can use these functions:

  • trimStart — to remove spaces at the beginning of the string
  • trimEnd — to remove spaces at the end of the string
  • trim — to do both actions at once and remove leading and trailing whitespace

Our base string won’t suffice to demonstrate this example, so we’ll create another one.

const stringWithSpaces = ' I learn JS with Coderslang every day '; console.log(stringWithSpaces.trimStart()); //'I learn JS with Coderslang every day ' console.log(stringWithSpaces.trimEnd()); //' I learn JS with Coderslang every day' console.log(stringWithSpaces.trim()); //'I learn JS with Coderslang every day' 

How to convert a string to the UPPERCASE or the lowercase

To change all characters of the string to the uppercase you can use the function toUpperCase and for the lowercase, you can use toLowerCase .

console.log(s.toUpperCase()); // I AM GOING TO BECOME A FULL STACK JS DEV WITH CODERSLANG console.log(s.toLowerCase()); // i am going to become a full stack js dev with coderslang 

Once again, notice that the original string never changes, as strings are immutable in JavaScript. These functions just return a new string with the desired changes.

How to replace a character in a string with a different one

To replace a character with another one in JS, you can use the replace function. Pass it two strings, and it will replace the first string with the second one.

console.log(s.replace(' ', '!')) // I!am going to become a FULL STACK JS Dev with Coderslang console.log(s.replace('I am', 'You are')) // You are going to become a FULL STACK JS Dev with Coderslang 

You might be surprised with the result as replace was applied only once. But that’s how it works in the base case.

If you want to change all occurrences of a substring, you should use the replaceAll function.

console.log(s.replaceAll(' ', '!')) // I!am!going!to!become!a!FULL!STACK!JS!Dev!with!Coderslang 

Take a note, that depending on your javascript runtime environment, you might run into the error

TypeError: s.replaceAll is not a function

If you do, then replaceAll isn’t supported in your environment and you can either implement it yourself or use a regular expression with the g flag. This will instruct replace to be applied globally.

const regex = new RegExp(' ', 'g'); const s = 'I am going to become a FULL STACK JS Dev with Coderslang'; console.log(s.replace(regex, '!')); // I!am!going!to!become!a!FULL!STACK!JS!Dev!with!Coderslang 

Regular expressions are a very powerful tool, so make sure to learn them if you haven’t already.

That concludes the review of the most useful built-in String functions in JS . Is there something else you want to add to this article or maybe request a new one?

You can find us on Twitter as @coderslang or on Telegram as t.me/coderslang to share your thoughts and suggestions.

Источник

How to Execute JavaScript Code Stored in a String?

Labrador retriever puppy walking on green grass

Sometimes, we have a JavaScript string with code in it that we want to run.

In this article, we’ll look at how to execute JavaScript code stored in a string.

Create a New Function with the Function Constructor

We can create a new function from our JavaScript code string with the Function constructor.

For instance, we can write:

const code = "alert('Hello World'); let x = 100"; const F = new Function(code); F(); 

to create the code string and store it into the code variable.

Then we pass code into the Function constructor to create a function from it.

And then we call F to run the function.

Use the setTimeout Function

We can also pass in the JavaScript code string into the setTimeout function to run the code string.

const code = "alert('Hello World'); let x = 100"; setTimeout(code, 1); 

We pass code as the first argument of the setTimeout function to run it.

The 2nd argument is the delay in milliseconds before running the function.

Don’t Use the eval Function

We shouldn’t use the eval function to run code from a string.

This is because anyone can easily inject code into it, which is a big security risk.

Also, it creates its own scope, which means it may do things we don’t expect.

So we shouldn’t write code like:

const code = "alert('Hello World'); let x = 100"; eval(code) 

Conclusion

We can run JavaScript code that’s stored in a string with JavaScript by creating a function from it with the Function constructor or pass it into the setTimeout function.

Источник

Читайте также:  Test php scripts online
Оцените статью