I am supposed to write a JavaScript function which inserts the character/s between only two consecutive Hash ( #
) symbols. For an example: If input string is:
var str = "#TIME##MONEY#";
Then output string must be "#TIME#IS#MONEY#"
You can use the replace() method.
var str = "#TIME##MONEY#"; var insert = 'IS' var newstr = str.replace('##', '#'+insert+'#') console.log(newstr);
Splice the string where you find ## and concat the string
var str = "#TIME##MONEY#"; for (i = 0; i < str.length; i++) { if (str[i] == '#' && str[i + 1] == '#') { newStr = str.slice(0, i+1) + 'abc' +str.slice(i + 1, str.length); } } console.log(str) console.log(newStr)
Just use replace
// Once var str = "#TIME##MONEY#"; document.write(str.replace('##','#IS#')); //more than once var str2 ="#TIME##MONEY##TIME##MONEY#"; while(str2.indexOf('##') != -1) { str2 = str2.replace('##','#IS#'); } document.write('<br />'+str2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.