Need to replace character from a long string, so in SAC we have predefine function to replace a specific character from string, as we know SAC based on JavaScript but not all javascript code are works here, so here we have replace() function to replace that string.

But there is an issue its can only one time, like if you have (Apple,Mango,Banana) and you want to replace comma(,) with – (hyphen) so replace function will only return as (Apple-Mango, Banana), so thats why here is one issue, but there is one perfect when to replace char from whole string, just follow the article.

One Way with Replace Function

Syntax

String.replace("will_replce","to_this");

Example

var cars = "Tesla, Bugatti, Audi, BMW";
var cars_new_name = cars.replace(",","-");

//output: Tesla - Bugatti, Audi, BMW

So this is one problem, its only replacing the first one char where its find the replace value.

Another Way with split and join Function

Here we will use Split function to split all string into array and then we will use join to combine all array elements into single string.

Syntax for Split()

var cars = "Tesla, Bugatti, Audi, BMW";
var mycars = cars.split(","); // it will split all value into array by comma(,)

//output: ["Tesla","Bugatti","Audi","BMW"]

Syntax for Join()

var cars = ["Tesla","Bugatti","Audi","BMW"];
var mycars = cars.join("|"); //combine all elements with | (symbol)

//output: Tesla | Bugatti | Audi | BMW

Complete Example

var cars = "Tesla, Bugatti, Audi, BMW";
var cars_new_name = cars.split(",").join("-");

//output: Tesla - Bugatti - Audi - BMW

Using this methods, we can replace char easily from string.

Sara Sampaio

Sara Sampaio

Author Since: March 10, 2022

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x