Technology Blog Posts by Members
cancel
Showing results for 
Search instead for 
Did you mean: 
rohitchouhan
Participant
3,743


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.
1 Comment