# How to replace characters except last with a mask character in JavaScript?

JavaScript has a built-in function called replace() that can be used to replace characters in a string. This function takes two arguments: the first argument is the character or characters to be replaced, and the second argument is the character or characters to replace them with.

## Syntax

Following is the syntax to replace characters except last with a specified mask −

str.replace(/.(?=.)/g, "x");


The first argument to the replace() method is character/s to be replaced. We pass a regular expression for all characters except last as the first argument to the replace method. All characters except the last are replaced with a specified mask ‘x’.

## Algorithm

• STEP 1 − Create a variable named str and assign the sting to it.

• STEP 2 − Replace the characters using the String replace() method. Use the syntax discussed above.

• STEP 3 − Display the string with replaced characters.

## Example 1

In the program below, we replace all characters except the last one with a specified mask character ie. “x”. We use the above-defined syntax of the replace method.

<html>
<body>
<div id="result1"></div>
<div id="result2"></div>
<script>
var str = "Hello world";
document.getElementById("result1").innerHTML = "Original String: " + str
var newStr = str.replace(/.(?=.)/g, "x");
document.getElementById("result2").innerHTML = "String after replacement: " + newStr
</script>
</body>
</html>


In the example above, the replace() function replaces all characters except the last one with the character "x".

If you want to replace only the first occurrence of a character, you can use the replace() function like this −

var str = "Hello world!";
var newStr = str.replace("l", "x", 1);


## Example 2

In the example below, we replace all characters except last with a mask character. We take the string and mask character from the user.

<!doctype html>
<html>
<title>Examples</title>
<body>
<p>Enter String: </p>
<input type="text" id="myStr" value="">
<p> String after replacement:</p>
<div id="result"></div>
<button onclick="replaceStr()">Replace</button>
<script>
function replaceStr() {
var str = document.getElementById("myStr").value;