Hướng dẫn replace space in javascript

Comprehensive unencrypted answer for newbies et al.

This is for all of the dummies like me who test the scripts written by some of you guys which do not work.

The following 3 examples are the steps I took to remove special characters AND extra spaces on the following 3 websites [all of which work perfectly] {1. EtaVisa.com 2. EtaStatus.com 3. Tikun.com} so I know that these work perfectly.

We have chained these together with over 50 at a time and NO problems.

// This removed special characters + 0-9 and allows for just letters [upper and LOWER case]

function NoDoublesPls1[]
{
var str=document.getElementById["NoDoubles1"];
var regex=/[^a-z]/gi;
str.value=str.value.replace[regex ,""];
}

// This removed special characters and allows for just letters [upper and LOWER case] and 0-9 AND spaces

function NoDoublesPls2[]
{
var str=document.getElementById["NoDoubles2"];
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace[regex ,""];
}

// This removed special characters and allows for just letters [upper and LOWER case] and 0-9 AND spaces // The .replace[/\s\s+/g, " "] at the end removes excessive spaces // when I used single quotes, it did not work.

function NoDoublesPls3[]
{    var str=document.getElementById["NoDoubles3"];
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace[regex ,""] .replace[/\s\s+/g, " "];
}

::NEXT:: Save #3 as a .js // I called mine NoDoubles.js

::NEXT:: Include your JS into your page

 

Include this in your form field:: such as


So that it looks like this


This will remove special characters, allow for single spaces and remove extra spaces.


🏠 Go back to the homepage

Find out how to use a regex to replace all white space inside a string using JavaScript

Replacing all the white space inside a string is a very common need.

For example I last used this inside an API endpoint that received an image. I used the original image name to store it, but if it contained a space it was breaking my functionality [or other special chars, but let’s focus on spaces]

So I researched the best way to do what I wanted. Turns out, a regular expression was what I needed!

Here it is, in full

const name = 'Hi my name is Flavio'
name.replace[/\s/g, ''] //HimynameisFlavio

The \s meta character in JavaScript regular expressions matches any whitespace character: spaces, tabs, newlines and Unicode spaces. And the g flag tells JavaScript to replace it multiple times. If you miss it, it will only replace the first occurrence of the white space.

Remember that the name value does not change. So you need to assign it to a new variable, if needed:

const name = 'Hi my name is Flavio'
const nameCleaned = name.replace[/\s/g, '']

Examples

Replace Microsoft:

Nội dung chính

  • Definition and Usage
  • Return Value
  • More Examples
  • Browser Support
  • Introduction to the JavaScript String replace[] method
  • Using regular expressions
  • Using a replacement function
  • What does replace method do?
  • What is $1 in replace JavaScript?
  • What is difference between replace and replaceAll in JavaScript?
  • What is replace [/ g in JavaScript?

let text = "Visit Microsoft!";
let result = text.replace["Microsoft", "W3Schools"];

Try it Yourself »

A global replacement:

let text = "Mr Blue has a blue house and a blue car";
let result = text.replace[/blue/g, "red"];

Try it Yourself »

More examples below.

Definition and Usage

The replace[] method searches a string for a value or a regular expression.

The replace[] method returns a new string with the value[s] replaced.

The replace[] method does not change the original string.

Note

If you replace a value, only the first instance will be replaced. To replace all instances, use a regular expression with the g modifier set.

Read more about regular expressions in our:

  • RegExp Tutorial
  • RegExp Reference

Syntax

string.replace[searchValue, newValue]

Parameters

Parameter Description
searchValue Required.
The value, or regular expression, to search for.
newValue Required.
The new value [to replace with].

Return Value

Type Description
A string A new string where the specified value[s] has been replaced.

More Examples

A global, case-insensitive replacement:

let text = "Mr Blue has a blue house and a blue car";
let result = text.replace[/blue/gi, "red"];

Try it Yourself »

A function to return the replacement text:

let text = "Mr Blue has a blue house and a blue car";
let result = text.replace[/blue|house|car/gi, function [x] {
  return x.toUpperCase[];
}];

Try it Yourself »

Browser Support

replace[] is an ECMAScript1 [ES1] feature.

ES1 [JavaScript 1997] is fully supported in all browsers:

Chrome IE Edge Firefox Safari Opera
Yes Yes Yes Yes Yes Yes

Summary: in this tutorial, you’ll how to use JavaScript String replace[] method to replace a substring in a string with a new one.

Introduction to the JavaScript String replace[] method

The following shows the syntax of the replace[] method:

let newStr = str.replace[substr, newSubstr];

Code language: JavaScript [javascript]

The JavaScript String replace[] method returns a new string with a substring [substr] replaced by a new one [newSubstr].

Note that the replace[] method doesn’t change the original string. It returns a new string.

The following example uses the replace[] to replace the JS in the string 'JS will, JS will rock you' wit the new substring JavaScript:

let str = 'JS will, JS will rock you!'; let newStr = str.replace['JS','JavaScript']; console.log[newStr];

Code language: JavaScript [javascript]

Output:

JavaScript will, JS will rock you!

Code language: JavaScript [javascript]

As you can see from the output, only the first occurrence of the substring JS was replaced with the new substring JavaScript.

To replace all occurrences of a substring in a string with a new one, you must use a regular expression.

Using regular expressions

The replace[] method fully supports regular expressions:

let newStr = str.replace[regexp, newSubstr];

Code language: JavaScript [javascript]

In this syntax, the replace[] method find all matches in the str, replaces them by the newSubstr, and returns a new string [newStr].

The following example uses the global flag [g] to replace all occurrences of the JS in the str by the JavaScript:

let str = 'JS will, JS will rock you!'; let newStr = str.replace[/JS/g,'JavaScript']; console.log[newStr];

Code language: JavaScript [javascript]

Output:

JavaScript will, JavaScript will rock you!

Code language: JavaScript [javascript]

If you want to ignore cases for searching and replacement, you can use the ignore flag [i] in the regular expression like this:

let str = 'JS will, Js will rock you!'; let newStr = str.replace[/JS/gi,'JavaScript']; console.log[newStr];

Code language: JavaScript [javascript]

Output:

JavaScript will, JavaScript will rock you!

Code language: JavaScript [javascript]

Using a replacement function

Instead of passing a newSubstr to the second parameter of the replace[] method, you can pass a replacement function as follows:

let newStr = str.replace[substr | regexp, replacer];

Code language: JavaScript [javascript]

In this syntax, the replace[] method will invoke the replacer function after the match has been performed. It then uses the result of this function as the replacement string.

If you use the global flag [g] in the regular expression, the replace[] method will invoke the replacer function for every match. For example, if there are three matches, the replace[] method will invoke the replacer[] function three times.

The replacer[] function has the following syntax:

function replacer[match, p1, p2, ..., offset, string];

Code language: JavaScript [javascript]

The following are the meaning of each parameter:

  • match: is the matched substring.
  • p1, p2, …pn are the nth string found by a parenthesized capture group provided by the regular expression.
  • offset: is the offset of the matched substring within the whole string being searched.
  • string: is the whole string being examined.

The following example uses the replace[] function to change the substrings apples and bananas to uppercase. It passes a replacer function into the replace[] function:

let str = "I like to eat, eat, eat apples and bananas"; let re = /apples|bananas/gi; let newStr = str.replace[re, [match] => { console.log[{match}]; return match.toUpperCase[]; }]; console.log[newStr];

Code language: JavaScript [javascript]

Output:

{match: "apples"} {match: "bananas"} I like to eat, eat, eat APPLES and BANANAS

Code language: JavaScript [javascript]

Summary

  • Use the replace[] method to return a new string with a substring replaced by a new one.
  • Use a regular expression with the global flag [g] to replace all occurrences of a substring with a new one.

Was this tutorial helpful ?

What does replace method do?

The replace[] method searches a string for a specified character, and returns a new string where the specified character[s] are replaced.

What is $1 in replace JavaScript?

In your specific example, the $1 will be the group [^| ] which is "position of the start of string [zero-width], or a single space character". So by replacing the whole expression with that, you're basically removing the variable theClass and potentially a space after it.

What is difference between replace and replaceAll in JavaScript?

3.1 The difference between replaceAll[] and replace[] If search argument is a string, replaceAll[] replaces all occurrences of search with replaceWith , while replace[] only the first occurence. If search argument is a non-global regular expression, then replaceAll[] throws a TypeError exception.

What is replace [/ g in JavaScript?

The "g" that you are talking about at the end of your regular expression is called a "modifier". The "g" represents the "global modifier". This means that your replace will replace all copies of the matched string with the replacement string you provide.

Chủ Đề