String replacement in JavaScript - javascript

I have two strings:
var str1 = '8***8***';
var str2 = '898-8293';
How can i wrap the digits found in string one, with html elements on the second string, like so:
'<b>8</b>98-<b>8</b>293'
Note: Not all '8' digits are wrapped.
[EDIT]
Thanks to Soufiane Hassou and voyager the following worked:
<script type="text/javascript">
var str1 = '8***8***';
var str2 = '898-8293';
var result = [];
var arr1 = str1.split('');
var arr2 = str2.split('');
for (var i = 0; i < arr2.length; i++) {
if (arr1[i] == arr2[i]) {
result.push('<b>' + arr2[i] + '</b>');
}
else {
result.push(arr2[i]);
}
}
var newStr = result.join('');
</script>

highlight_string = function(str, mask){
var result='';
str1 = mask.split("");
str2 = str.split("");
for(int i = 0; i < str2.length; i++) {
if((str1[i] == "*") || (str2[i] == str1[i])) {
result+='<b>' + str1[i] + '</b>';
}
else { result+=str2[i]; }
}
return result;
}
Expanding on Soufiane Hassou's answer, I think this is closer to what you are looking for.

var result='';
for(int i = 0; i < str2.length; i++) {
if(str2[i] == str1[i] {
result+='<b>' + str1[i] + '</b>';
}
else { result+=str2[i]; }
}
Is this what you want to do?

It looks like you are actually trying to do isn't combine the two strings, but to match a regular expression in str1 to a value in str2. If that's the case you would want to change str1 a regular expression and test str2 against it. Something like this:
/[8]\d{2}[-][8]\d{3}/.test('898-8293');
//or
/[8]\d*[-][8]\d*/.test('898-8293');
//or
/[8].*[-][8].*/.test('898-8293');
//or
/[8].*[8].*/.test('898-8293');

var str2 = '898-8293';
var str3 = str2.replace(/(\d{1})(\d{2})(-)(\d{1})(\d{3})/g, '<br>$1</br>$2$3<br>$4</br>$5');
alert(str3);
For the win.

Related

Without using a data structure, display whether each character in a string is unique

Without using a data structure, I need to display whether each character in a string is unique or not.
I wrote the code and it works for paa but it doesn't work for pak.
var String = "paa"
//var String = "pak"
var splittedString = String.split();
for(i = 0; i < splittedString.length; i++) {
if(splittedString[i] === splittedString[i+ 1] ||
splittedString[i+1] === splittedString[i + 2]) {
console.log("not unique string");
} else {
console.log("its an unique string")
}
}
It is clearly stated in the problem don't need to use the data structure. I saw above answers using an array. I try to solve this issue in C#. Let me know if you have any feedback.
public bool IsUnique(string text)
{
if (text.Length > 256) return false;
for (var indx = 0; indx < text.Length; indx++)
{
for (var jndx = indx + 1; jndx < text.Length; jndx++)
{
// compare character
if (text.Substring(indx, 1) == text.Substring(jndx, 1) )
{
return false;
}
}
}
return true;
}
Just to show the needed change in your code, plus nice output as per Emile's request:
var str = "palace";
//var str = "pak";
var splittedString = str.split('');
for (i=0; i<splittedString.length; i++) {
var c = splittedString[i];
var unique = true;
for (j=0; j <splittedString.length; j++) {
if (i==j) continue;
if (c === splittedString[j]) {
unique = false;
break;
}
}
console.log("'" + c + "' is" + (unique ? '': ' not') + " unique character");
}
First you sort the characters in the string and then compare each one to the next.
The program with regex may look like below
var str = "alphabet";
var sstr = str.split('').sort().join('');
var result = /(.)\1/.test(sstr);
console.log(sstr + " has dups: " + result)

Identify palindromes in a sentence

A lot of solutions I found here are giving true or false after checking if a string is a palindrome. I have a function that checks if a string is a palindrome or not:
function palindrome(myString){
/* remove special characters, spaces and make lowercase*/
var removeChar = myString.replace(/[^A-Z0-9]/ig, "").toLowerCase();
/* reverse removeChar for comparison*/
var checkPalindrome = removeChar.split('').reverse().join('');
/* Check to see if myString is a Palindrome*/
if(removeChar === checkPalindrome){
document.write("<div>"+ myString + " is a Palindrome <div>");
}else{
document.write("<div>" + myString + " is not a Palindrome </div>");
}
}
palindrome("Oh who was it I saw, oh who?")
palindrome("Madam")
palindrome("Star Wars")
But this is not quite what I want. It's just checking if the string is a palindrome or not. I want to update the function so that it identifies all of the palindromes in a sentence instead of giving it true or false. So if there's a sentence like this - "Madam and John went out at noon" It will list the palindromes in that sentence - "Madam, noon"
Any help in this would be appreciated!
function findPalindromes(str, min) {
min = min || 3;
var result = [];
var reg = str.toLowerCase();
var reg = reg.replace(/[^a-z]/g, ''); // remove if you want spaces
var rev = reg.split("").reverse().join("");
var l = reg.length;
for (var i = 0; i < l; i++) {
for (var j = i + min; j <= l; j++) {
var regs = reg.substring(i, j);
var revs = rev.substring(l - j, l - i);
if (regs == revs) {
result.push(regs);
}
}
}
return result;
}
var str1 = "Madam and John went out at noon";
console.log(str1, findPalindromes(str1));
var str2 = "\"Amore, Roma\" and \"There's no 'x' in Nixon\" are palindromes.";
console.log(str2, findPalindromes(str2));
function findPalindromes(sentence) {
const words = sentence.replace(/[^\w\s]/gi, '').split(' ');
const palindromes = words.filter(isPalindrome);
return palindromes;
}
function isPalindrome(word) {
if (word.length <= 0) return false;
word = word.toLowerCase();
for (let i = 0; i < word.length / 2; i++) {
if (word[i] !== word[word.length - 1 - i]) return false;
}
return true;
}
https://jsfiddle.net/ewezbz22/1/

Palindrome function returns true when word isn't a palindrome

Could someone be kind enough to tell me why "almostomla" returns true in my code.
I have searched and have seen there are simpler versions but im so deep into this code now i need to make it work if at all possible.
Please excuse the terrible variable names, i was frustrated.
function palindrome(str) {
str = str.toLowerCase();
str = str.replace(/ /g, '').replace(/\./g, '').replace(/,/g, '');
for (var i = 0; i < str.length / 2; i++) {
for (var j = str.length - 1; j > str.length / 2 - 1; j--) {
var iDntKnow = str.charAt(i);
var iDntKnowEither = str.charAt(j);
if (iDntKnow === iDntKnowEither) {
return true;
} else {
return false;
}
}
}
}
Appreciate all answers.
While I can understand the frustration of wanting to make something work if you have put time into it, there is also something to be said for starting from the drawing board and not driving yourself crazy. The main problem I see with your code is that you have two loops when you only need one. The second loop is actually sabotaging you. I would suggest running a debugger (type "debugger" into your code and run) to see why.
I believe this is what you are trying to accomplish:
var palindrome = function(str) {
// Put any additional string preprocessing here.
for(var i = 0; i < str.length/2; i++) {
var j = str.length-i-1;
if (str[i] != str[j]) {
return false;
}
}
return true;
}
In this way you are comparing each mirrored element in the string to confirm if the string is a palindrome.
Your question seems to be answered by now.
If performance isn't an issue, why not just use this?
function palindrome(str) {
str = str.toLowerCase();
return (str.split().reverse().join() === str)
}
It splits the string into an array, reverses that and joins it back together. The result is compared to the original string.
You can only know if it's NOT a palindrome in each iteration.
Also, why using nested loops?
function palindrome(str) {
str = str.toLowerCase();
str = str.replace(/ /g, '').replace(/\./g, '').replace(/,/g, '');
for (var i = 0; i < str.length / 2; i++) {
if (str.charAt(i) !== str.charAt(str.length - i - 1)) {
return false;
}
}
return true;
}
This works:
function palindrome(string) {
string = string.toLowerCase();
for (var i = 0; i < Math.ceil(str.length/2); i++) {
var character1 = string.charAt(i);
var character2 = string.charAt(string.length-1-i);
if (character1 !== character2) {
return false;
}
}
return true;
}
Here is a version that omits spaces and commas:
var removeLetterFromString = function(string,letterPos){
var returnString = "";
for(var i = 0; i < string.length; i++){
if(i!==letterPos){
returnString=returnString+string.charAt(i);
}
}
return returnString;
};
var palindrome = function(string) {
string = string.toLowerCase();
var stringCheck="";
var recheck = true;
while(recheck){
recheck=false;
for(var i = 0; i < string.length; i ++){
if(string.charAt(i)===" "||string.charAt(i)===","){
string=removeLetterFromString(string,i);
}
}
for(var i = 0; i < string.length; i ++){
if(string.charAt(i)===" "||string.charAt(i)===","){
recheck=true;
}
}
}
if(string.length===0){
return false;
}
for (var i = 0; i < Math.ceil(string.length/2); i++) {
var j = string.length-1-i;
var character1 = string.charAt(i);
var character2 = string.charAt(j);
if (character1 !== character2) {
return false;
}
}
return true;
};

Insert dashes into a number

Any ideas on the following? I want to input a number into a function and insert dashes "-" between the odd digits. So 4567897 would become "456789-7". What I have so far is to convert the number into a string and then an array, then look for two odd numbers in a row and use the .splice() method to add the dashes where appropriate. It does not work and I figure I may not be on the right track anyway, and that there has to be a simpler solution.
function DashInsert(num) {
var numArr = num.toString().split('');
for (var i = 0; i < numArr.length; i++){
if (numArr[i]%2 != 0){
if (numArr[i+1]%2 != 0) {
numArr.splice(i, 0, "-");
}
}
}
return numArr;
}
The problem is you're changing the thing you're iterating over. If instead you maintain a separate output and input...
function insertDashes(num) {
var inStr = String(num);
var outStr = inStr[0], ii;
for (ii = 1; ii < inStr.length; ii++) {
if (inStr[ii-1] % 2 !== 0 && inStr[ii] % 2 !== 0) {
outStr += '-';
}
outStr += inStr[ii];
}
return outStr;
}
You can try using regular expressions
'4567897'.replace(/([13579])(?=[13579])/g, '$1-')
Regex Explained
So, we find an odd number (([13579]) is a capturing group meaning we can use it as a reference in the replacement $1) ensure that it is followed by another odd number in the non-capturing positive lookahead ((?=[13579])) and replace the matched odd number adding the - prefix
Here is the function to do it:
function dashes(number){
var numString = '';
var numArr = number.toString().split('');
console.log(numArr);
for(i = 0; i < numArr.length; i++){
if(numArr[i] % 2 === 1 && numArr[i+1] % 2 === 1){
numString += numArr[i] + '-';
}else{
numString += numArr[i];
}
}
console.log(numString);
}
dashes(456379);
Tested and everything.
Edit: OrangeDog's answer was posted earlier (by nearly a full half hour), I just wanted to make an answer which uses your code since you're almost there.
Using another array instead of splicing into one you were looping through (this happens to return a string using join):
var num = 4567897;
function DashInsert(num) {
var numArr = num.toString().split('');
var len = numArr.length;
var final = [];
for (var i = 0; i < len; i++){
final.push(numArr[i]);
if (numArr[i]%2 != 0){
if (i+1 < len && numArr[i+1]%2 != 0) {
final.push("-")
}
}
}
return final.join("");
}
alert(DashInsert(num));
function dashInsert(str) {
var arrayNumbers = str.split("");
var newString = "";
for (var i = 0; i < arrayNumbers.length; i++){
if(arrayNumbers[i] % 2 === 1 && arrayNumbers[i + 1] % 2 === 1){
newString = newString + arrayNumbers[i] + "-";
} else {
newString = newString + arrayNumbers[i];
}
}
return newString;
}
var result = dashInsert("3453246");
console.log(result);

Replace the every 3rd comma in a string

So it I have the string:
var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
How would you replace every 3rd comma with an ! (For example)? It would look something like:
var str = "blue,red,green!orange,yellow,brown!black,teal,purple!gold,silver,white"
After scrapping together some things I found, I came up with this:
var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
function replaceIndex(string, at, repl) {
return string.replace(/\S/g, function(match, u) {
if( u === at ) return repl;
return match;
});
var total_items = str.split(",").length - 1;
var counter = 1;
for (var i = 0; i < str.length; i++){
if (str.charAt(i) == ","){
if (total_items%counter == 0){
replaceIndex(str, i, "},{");
}
counter++;
}
}
}
You can do this with some regex magic:
str = str.replace(/([^,],[^,]*?,[^,]*?),/g, '$1!');
Try
var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
str = str.replace(/(([^,]*,){2}([^,]*)),/g, '$1!')

Categories

Resources