By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
Daily News Circuit
  • Home
  • World
    Health

    Selective: 7 Easy Tips To Conceive Quickly – Daily News Circuit

    By admin 9 Min Read
    Healthy Food

    Selective: Not Your Mama’s Magic Cookies – Daily News Circuit

    By admin November 28, 2023
    Insider

    Selective: Bank of England governor warns of tough times ahead in battle to lower inflation – Daily News Circuit

    By admin November 28, 2023
  • Technology
    Healthy Food

    Selective: Not Your Mama’s Magic Cookies – Daily News Circuit

    #Mamas #Magic #Cookies Buckle up kids, day 2 of #AKCookieWeek is an…

    By admin 11 Min Read
    Insider
    Selective: Bank of England governor warns of tough times ahead in battle to lower inflation – Daily News Circuit
    Science
    Selective: Robots with squidgy paws could navigate uneven terrain – Daily News Circuit
    Technology
    Selective: AWS brings Amazon One palm-scanning authentication to the enterprise – Daily News Circuit
    Computer
    Selective: Premium 1440p gaming monitor discounted in last-minute Cyber Monday deal – Daily News Circuit
  • Insider

    “Rowan Glen Revitalized: Yoghurt Maker Returns with Management Buyout”.

    #Yoghurt #maker #Rowan #Glen #starts #production #management #buyout New boss vows 'We will start small and…

    By admin

    Court Upholds Right to Keep Edinburgh Strip Clubs Open

    #Ban #Edinburgh #strip #clubs #quashed #court The measures were due to come into force in April,…

    By admin

    “Record-Breaking £6 Billion in Scotch Whisky Exports Defies Domestic Challenges”

    #Scotch #whisky #exports #billion #time #domestic #headwinds Meanwhile, Scottish salmon was UK’s biggest food export during…

    By admin

    “Unwinding of Regulations on Al Fresco Seating Anticipated by Late March!”

    #Relaxation #rules #outdoor #seating #expected #March The changes have all been backed in a consultation by…

    By admin

    “A Bright Future Ahead: Construction of 30 New Council Houses in East Lothian Begins!”

    #Construction #council #houses #East #Lothian #underway The development is scheduled for completion towards the end of…

    By admin

    “Glasgow Apprentice Contestant Forced to Exit Show Amidst Health Crisis”

    #Glasgow #Apprentice #contestant #leaves #show #due #health #issues He becomes the second contestant to quit this…

    By admin

    “A New Era: Expro Announces Acquisition of DeltaTek Global”

    #Expro #acquires #DeltaTek #Global The deal should help with the Aberdeen-based company's international growth plans

    By admin

    The UK Narrowly Escapes Recession as Economy Flatlines at 2022’s End

    #narrowly #avoids #recession #economy #flatlines When counting to two decimal places, the UK managed 0.01% growth…

    By admin
  • My Bookmarks
Reading: “Unlock the Power of JavaScript: String Concatenation and Substitution Techniques”
Sign In
  • Join US
Daily News CircuitDaily News Circuit
Aa
  • Bussiness
  • The Escapist
  • Entertainment
  • Science
  • Technology
  • Insider
Search
  • Home
  • Categories
    • Technology
    • Entertainment
    • The Escapist
    • Insider
    • Bussiness
    • Science
    • Health
  • Bookmarks
    • Customize Interests
    • My Bookmarks
  • More DNC
    • Blog Index
    • Sitemap
Have an existing account? Sign In
Follow US
© Daily News Circuit. 2023. All Rights Reserved.
Daily News Circuit > Blog > Technology > Software > “Unlock the Power of JavaScript: String Concatenation and Substitution Techniques”
Software

“Unlock the Power of JavaScript: String Concatenation and Substitution Techniques”

admin
Last updated: 2023/02/13 at 8:33 PM
By admin 9 Min Read
Share
SHARE

#JavaScript #String #Methods #Concatenation #Substitution

Contents
How to Concatenate Strings in JavaScriptSyntax of concat () in JavaScriptExamples of concat () in JavaScriptHow to Replace Text in JavaScriptSyntax of replace() and replaceAll()Examples of replace() and replaceAll()How to Change Case in JavaScriptSyntax of toLowerCase() and toUpperCase()Examples of toLowerCase() and toUpperCase()Working with Characters and Unicode in JavaScriptSyntax of JavaScript Unicode MethodsExamples of Unicode MethodsMiscellaneous String Methods in JavaScriptlocaleCompare() SyntaxExamples of localeCompare()repeat() SyntaxExamples of repeat() MethodFinal Thoughts on JavaScript String Methods for Concatenation and Substitution

JavaScript tutorial

Welcome to the third and final article in our series on JavaScript string methods. The JavaScript Methods for Searching Strings tutorial presented the complete list of JavaScript (JS) methods for working with strings, along with detailed explanations of JavaScript’s eight string searching methods. In the last article, we looked at methods for trimming, padding, and extracting strings. This installment will cover how to concatenate strings, replace part of a string, change its case, and a whole lot more!

You can check out the previous two parts in this series here:

How to Concatenate Strings in JavaScript

Concatenation is the process of appending one string to the end of another string. You are probably already familiar with the + string concatenation operator. The difference is that concat () coerces its arguments directly to String objects, while + coerces its operands to primitives first.

Syntax of concat () in JavaScript

string.concat (str1)
string.concat (str1, str2)
string.concat (str1, str2, /* ..., */ strN)

Examples of concat () in JavaScript

const greeting = "Hi ";
// Outputs "Hi Rob. Have a good one!"
console.log(greeting.concat("Rob", ". Have a good one."));

const greetList = ["Rob", " and ", "George", "!"];
// Outputs "Hi Rob and George!"
console.log(greeting.concat(...greetList));

//Type conversion
"".concat ({}); // "[object Object]"
"".concat ([]); // ""
"".concat (null); // "null"
"".concat (true); // "true"
"".concat (6, 7); // "67"

How to Replace Text in JavaScript

To replace text in a JavaScript string, web developers have two choices: the replace() and replaceAll() methods. Both methods search a string for a specific string or regular expression. The replace() method substitutes the first match with the specified value and returns it as a new string. Meanwhile, as the name suggests, replaceAll() replaces all matches.

Syntax of replace() and replaceAll()

string.replace(pattern, replacement)
string.replaceAll(pattern, replacement)

Examples of replace() and replaceAll()

In practice, both methods are virtually identical, because replaceAll() will not replace all matches unless you use a RegEx for the pattern and include the g flag. As seen in the examples below, doing so with replace() will yield the same results!

let str="I studied at the School of Rock as well as the school of life!";
// Using an exact string pattern
console.log(str.replace('School', 'Institute'));
// Case insensitive
console.log(str.replace(/school/i, 'Institute'));
// Replaces ALL occurences
console.log(str.replace(/school/ig, 'Institute'));
// Replaces ALL occurences using replaceAll()
console.log(str.replaceAll(/school/ig, 'Institute'));
// Throws a TypeError because the g flag is required when using replaceALL()
console.log(str.replaceAll(/school/i, 'Institute'));

Note that replaceAll() is an ES2021 feature and does not work in Internet Explorer.

Read: Best Online Courses to Learn JavaScript

How to Change Case in JavaScript

You can convert a string to upper and lower case using the toUpperCase() and toLowerCase() methods, respectively.

Syntax of toLowerCase() and toUpperCase()

Neither method accepts parameters, so they are very simple to use:

string.toUpperCase()
string.toLowerCase()

Examples of toLowerCase() and toUpperCase()

const sentence="Robert likes to eat at The Greasy Spoon Diner.";
// Output: "robert likes to eat at the greasy spoon diner."
console.log(sentence.toLowerCase());

// Output: "ROBERT LIKES TO EAT AT THE GREASY SPOON DINER."
console.log(sentence.toUpperCase());

Working with Characters and Unicode in JavaScript

JavaScript strings are based on Unicode, with each character being represented by a byte sequence of 1-4 bytes. Therefore, JavaScript offers a number of methods to work with individual characters and bytes.

Here is a recap of JavaScript’s methods for working with characters and Unicode:

  • charAt(): returns character at a specified index in string
  • charCodeAt(): returns Unicode of the character at given index
  • fromCharCode(): returns a string from the given UTF-16 code units
  • codePointAt(): returns the Unicode point value at given index
  • fromCodePoint(): returns a string using the given code points

Syntax of JavaScript Unicode Methods

string.charAt(index)
string.charCodeAt(index)
string.codePointAt(index)
String.fromCharCode(n1, n2, ..., nX)
String.fromCodePoint(n1, n2, ..., nX)

charAt(), charCodeAt(), and codePointAt() all accept an integer between 0 and the string length minus 1. If the index cannot be converted to the integer or no index is provided, the default is 0 and the first character of the string is returned.

The fromCharCode() and fromCodePoint() methods are both static; fromCharCode() accepts a sequence of Unicode code points, while fromCodePoint() accepts one or more Unicode values to be converted.

Examples of Unicode Methods

const str = "Outside my window there’s an open road";
// charAt() ***********************************************
// No index was provided, used 0 as default
console.log(str.charAt()); // O
// Explicitly providing 0 as index
console.log(str.charAt(0)); // O
console.log(str.charAt(3)); // s
console.log(str.charAt(999)); // ""

// charCodeAt() *******************************************
// No index was provided, used 0 as default
console.log(str.charCodeAt()); // 79
// Explicitly providing 0 as index
console.log(str.charCodeAt(0)); // 79
console.log(str.charCodeAt(3)); // 115
console.log(str.charCodeAt(999)); // NaN

// codePointAt() *******************************************
"ABC".codePointAt(0); // 65
"ABC".codePointAt(0).toString(16); // 41

"😍".codePointAt(0); // 128525
"\ud83d\ude0d".codePointAt(0); // 128525
"\ud83d\ude0d".codePointAt(0).toString(16); // 1f60d
"😍".codePointAt(1); // 56845
"\ud83d\ude0d".codePointAt(1); // 56845
"\ud83d\ude0d".codePointAt(1).toString(16); // de0d

"ABC".codePointAt(40); // undefined

// fromCharCode() ******************************************
// Outputs "½+¾="
console.log(String.fromCharCode(189, 43, 190, 61));

// fromCodePoint() *****************************************
// Outputs "☃★♲你"
console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));

Read: Top Collaboration Tools for Web Developers

Miscellaneous String Methods in JavaScript

A couple of String methods do not fall into any of the above categories. They are localeCompare(), which compares two strings in the current locale, and repeat(), which returns a string by repeating it given times. Let’s take a look at each of them.

localeCompare() Syntax

localeCompare(compareString)
localeCompare(compareString, locales)
localeCompare(compareString, locales, options)

Of the three input parameters above, only the compareString is required.

The locales should be a string, or array of strings, with a BCP 47 language tag.

The options are an object that adjust the output format.

Examples of localeCompare()

// The letter "a" is before "c" resulting in a negative value
"a".localeCompare("c"); // -2 or -1 (or some other negative value)

// Alphabetically the word "check" comes after "against" resulting in a positive value
"check".localeCompare("against"); // 2 or 1 (or some other positive value)

// "a" and "a" are equivalent resulting in a neutral value of zero
"a".localeCompare("a"); // 0

console.log("ä".localeCompare("z", "de")); // a negative value: in German, ä sorts before z
console.log("ä".localeCompare("z", "sv")); // a positive value: in Swedish, ä sorts after z

// in German, ä has a as the base letter
console.log("ä".localeCompare("a", "de", { sensitivity: "base" })); // 0
// in Swedish, ä and a are separate base letters
console.log("ä".localeCompare("a", "sv", { sensitivity: "base" })); // a positive value

repeat() Syntax

The repeat() method’s one input parameter is an integer of 0 or above, indicating the number of times to repeat the string. Passing in a negative number results in a RangeError.

repeat(count)

Examples of repeat() Method

"abc".repeat(-1); // RangeError
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
'abc'.repeat(1 / 0); // RangeError

You will find a demo of today’s methods on Codepen.io.

Final Thoughts on JavaScript String Methods for Concatenation and Substitution

In this third and final web development tutorial in our series on JavaScript string methods, we learned how to concatenate strings, replace part of a string, change its case, and a whole lot more. All of the methods presented here today should work in all modern browsers, unless otherwise indicated.

Read more web development and JavaScript programming tutorials.

You Might Also Like

Selective: Microsoft releases Orca 2 to teach small language models how to reason – Daily News Circuit

Selective: What Amazon announced at AWS re:Invent so far – Daily News Circuit

Selective: How to Play Grand Poo World 3 – Daily News Circuit

Selective: News from third-party providers out of AWS re:Invent – Daily News Circuit

Selective: Capital One open-sources new project for generating synthetic data – Daily News Circuit

TAGGED: Concatenation, JavaScript, Power, String, Substitution, Techniques, Unlock
admin February 13, 2023
Share this Article
Facebook Twitter Email Copy Link Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Follow US

Find US on Social Medias

Facebook
Like

Twitter
Follow

Youtube
Subscribe

Telegram
Follow

Weekly Newsletter

Subscribe to our newsletter to get our newest articles instantly!

– Advertisement –

 

Popular News



edit
The Escapist

8 Mistakes That Will RUIN Your Weekend Trips Plan

Ruby Staff
Ruby Staff
August 30, 2021
10+ Pics That Prove Jennifer Is a Timeless Beauty
Medicaid Expansion Improves Hypertension and Diabetes Control
12 Summer Outfit Formulas for Lazy Girls Everywhere
Explained: How the President of US is Elected

Global Coronavirus Cases

Confirmed

0

Death

0


More Information:Covid-19 Statistics

More Popular from Daily News Circuit

Technology

“Revolutionary AI Apps Shake Up the Tech World as Bing Hits the Top Charts, Google and Mozilla Test Non-WebKit Browsers” – TechCrunch

By admin 30 Min Read

“Revolutionary AI Apps Shake Up the Tech World as Bing Hits the Top Charts, Google and Mozilla Test Non-WebKit Browsers” – TechCrunch

By admin
Health

“Invasion of Privacy? Uncovering the Risks of Contact Tracing Apps”

By admin 0 Min Read
- Advertisement -
Ad image
Technology

“Revolutionary AI Apps Shake Up the Tech World as Bing Hits the Top Charts, Google and Mozilla Test Non-WebKit Browsers” – TechCrunch

#apps #Bing #hits #Top #Charts #Google #Mozilla #test #nonWebKit #browsers #TechCrunch Welcome back to This Week…

By admin
Beautiful

The Unparalleled Splendor of the Outspoken Beauty Awards: Unveiling the Best Makeup Products of 2022!

#Outspoken #Beauty #Awards #Top #Makeup #Products The Outspoken Beauty Awards 2022 are here. Listen to today's…

By admin
Vacation

“Awe-Inspiring Quito: Unveiling the City’s 7 Reasons for Stealing Hearts & the Top 3 Places to Stay”

#reasons #Quito #steals #hearts #visitors #destinations #stay The city of Quito is the capital of Ecuador,…

By admin
Investment

“Harnessing the Power of Nature: A Tribute to Pitta – Achieving Sustainable Investing Through a Natural Capital Approach”

#Natural #Capital #Approach #Sustainable #Investing #Tribute #Pitta Goodbye, Pitta It was a sunny afternoon when I…

By admin
Technology

“Revolutionary AI Apps Shake Up the Tech World as Bing Hits the Top Charts, Google and Mozilla Test Non-WebKit Browsers” – TechCrunch

#apps #Bing #hits #Top #Charts #Google #Mozilla #test #nonWebKit #browsers #TechCrunch Welcome back to This Week…

By admin
Daily News Circuit

Stay in the loop and on the pulse of entertainment with Daily News Circuit – your ultimate source for sizzling news and electrifying videos from the heart of the entertainment world.

Categories

  • The Escapist
  • Entertainment
  • Bussiness

Quick Links

  • Advertise with us
  • Newsletters
  • Complaint
  • Deal

Copyright © 2023 Daily News Circuit | All Rights Reserved.

Removed from reading list

Undo
Welcome Back!

Sign in to your account

Lost your password?