Como Aparar Strings Em JavaScript

Uma boa prática ao usar valores de string de campos de formulário é remover os espaços em branco do início e do fim das strings — ou seja, aparar a string.

Neste post, vou descrever o que é um espaço em branco e um caractere terminador de linha em JavaScript.

Além disso, você lerá como aparar strings, também conhecido como remover espaços em branco e caracteres de terminação de linha do início e/ou fim da string.

1. Os espaços em branco e terminadores de linha

Antes de mergulhar nas funções de corte reais, vamos primeiro concordar com quais caracteres especiais as funções de corte estão removendo das strings.

Primeiro, o espaço em branco é qualquer caractere da lista a seguir:

  • ESPAÇO ( U+0020ponto de código)
  • TABULAÇÃO DE CARACTERES ( U+0009ponto de código)
  • TABULAÇÃO DE LINHA ( U+000BUponto de código)
  • FORM FEED (FF) ( U+000Cponto de código)
  • ESPAÇO NO-BREAK ( U+00A0ponto de código)
  • ESPAÇO SEM QUEBRA DE LARGURA ZERO ( U+FEFFUponto de código)
  • Qualquer outro personagem da categoria Separador de Espaço

Em palavras simples, os espaços em branco são caracteres que renderizados na tela criam um espaço em branco vazio.

Os caracteres de espaço em branco comuns são espaço ' 'e tabulação '\t'.

Em segundo lugar, o terminador de linha também é um conjunto especial de caracteres que consiste em:

  • LINE FEED ( U+000Aponto de código)
  • RETORNO DE CARRO ( U+000Dponto de código)
  • SEPARADOR DE LINHA ( U+2028ponto de código)
  • SEPARADOR DE PARÁGRAFO ( U+2029ponto de código)

O terminador de linha representa um caractere que existe no final de uma linha de texto e tem algum propósito especial.

Um caractere terminador de linha comum é o avanço de linha '\n', o que significa mover uma linha para frente.

2. Apare strings em JavaScript

Há situações em que você deseja limpar as strings que entram na entrada do aplicativo. Por exemplo, você definitivamente deseja cortar strings dos campos de formulário que representam um nome de usuário, nome, sobrenome, número de telefone etc.

JavaScript fornece 3 funções simples sobre como cortar strings.

2.1 string.trim()

string.trim()remove sequências de espaços em branco e terminadores de linha do início e do fim da string.

Vejamos alguns exemplos:

const name = '  Kate ';
name.trim(); // => 'Kate'
const phoneNumber = '\t  555-123\n ';
phoneNumber.trim(); // => '555-123'

Experimente a demonstração.

name.trim()remove os espaços do início e do fim da string. ' Kate 'torna-se 'Kate'.

phoneNumber.trim()também limpa as duas pontas: '\t 555-123\n 'torna -se '555-123'.

A função trim remove de ambas as extremidades das seqüências de strings de espaços em branco consecutivos e terminais de linha. Mas se um espaço em branco for encontrado entre duas letras, é claro que esse espaço em branco será preservado:

const fullName = '  Kate Smith  ';
fullName.trim(); // => 'Kate Smith'

Experimente a demonstração.

fullName.trim()remove os espaços do início e do fim da string, mas mantém o espaço entre as palavras Katee .Smith

2.2 string.trimStart()

string.trimStart()remove sequências de espaços em branco e terminadores de linha apenas do início da string.

const name = '  Jane ';
name.trimStart(); // => 'Jane '
const phoneNumber = '\t  555-123 \n';
phoneNumber.trimStart(); // => '555-123 \n'

Experimente a demonstração.

name.trimStart()remove os espaços apenas do início da string e não toca no espaço no final. ' Jane 'torna-se 'Jane '.

phoneNumber.trimStart()remove a sequência de espaços em branco e terminais de linha apenas desde o início. '\t 555-123 \n'torna-se '555-123 \n'.

2.3 string.trimEnd()

string.trimEnd()remove sequências de espaços em branco e terminadores de linha apenas do final da string.

const name = '  Jim ';
name.trimEnd(); // => '  Jim'
const phoneNumber = '\t  555-123 \n';
phoneNumber.trimEnd(); // => '\t  555-123'

Experimente a demonstração.

name.trimEnd()remove o único espaço do final e não toca na parte principal. ' Jim 'torna-se ' Jim'.

phoneNumber.trimEnd()apara a extremidade da corda também. '\t 555-123\n 'torna-se '\t 555-123'.

3. Conclusão

Os espaços em branco, como um espaço ou tabulação, são caracteres especiais que criam espaço vazio quando renderizados.

Também os terminais de linha, como o feed de linha, você pode encontrar no final das linhas em uma string de várias linhas.

Muitas vezes você pode achar útil remover esses caracteres especiais de uma string. As funções de corte do JavaScript podem ajudá-lo.

string.trim()remove sequências de espaços em branco e terminadores de linha do início e do fim da string, string.trimStart()remove-os do início e, finalmente, string.trimEnd()remove-os do final. 

Fonte: https://dmitrupavlutin.com/javascript-string-trim/

#javascript 

What is GEEK

Buddha Community

Como Aparar Strings Em JavaScript
Lowa Alice

Lowa Alice

1624399200

JavaScript Strings Tutorial

JavaScript Strings

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=09BwruU4kiY&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=6
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #strings #javascript strings #javascript strings tutorial

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.

Does your business need an interactive website or app?

Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.

The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.

Get your business app with JavaScript

For more inquiry click here https://bit.ly/31eZyDZ

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.

#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips

Ajay Kapoor

1626321063

JS Development Company India | JavaScript Development Services

PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.

With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.

Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.

Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.

#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company