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!')
Related
I have this function
function palindrome(str){
var myStr = "";
for (var index = str.length -1 ; index >=0; index--) {
myStr += str[index]
}
var res = myStr == str ? true : false;
return res;
}
It works with a single word , but if i checked such as "I did, did I?" , it don't works. How i can check is without using replace , join , reverse , etc... Only pure js . Thanks very much .
This is how i do it, run the loop both incremental and decremental fashion at the same time
function palindrome() {
var str = "dd dd";
var Ispalindrome = true;
for (var i = 0, j = str.length - 1; i < str.length && j >= 0; i++, j--) {
if (str[i] !== str[j]) {
Ispalindrome = false;
}
}
alert(Ispalindrome);
return Ispalindrome;
}
//Invoked
palindrome()
I have a < p > with 123456789 value
I need to convert my < p > value into 123.456.789 number. What's the easiest way to do this in js?
Try it using regex. The match() function creates an array and join('.') will join the array elements to the required output.
str = "123456789";
str = str.match(/.{1,3}/g).join('.')
console.log(str)
Try Using this function.
Useful for any number and for any delimeter you pass through.
function formatNumber(n, d) // n = number, d = delimeter
{
// round to 2 decimals if cents present
n = (Math.round(n * 100) / 100).toString().split('.');
var
myNum = n[0].toString(),
fmat = new Array(),
len = myNum.length,
i = 1, deci = (d == '.') ? '' : '.';
for (i; i < len + 1; i++)
fmat[i] = myNum.charAt(i - 1);
fmat = fmat.reverse();
for (i = 1; i < len; i++)
{
if (i % 3 == 0) {
fmat[i] += d;
}
}
var val = fmat.reverse().join('') +
(n[1] == null ? deci + '':
(deci + n[1])
);
return val;
}
var res = formatNumber(123456789,'.');
console.log(res);
You can use .match() with RegExp /\d{3}(?=\d{6}|\d{3}|$)/g to match three digits followed by six digits, three digits or end of string, chain .join() to array returned by .match() with parameter "."
var str = "123456789";
var res = str.match(/\d{3}(?=\d{6}|\d{3}|$)/g).join(".");
console.log(res);
Regex combined with html will be enough to get it to work beautifully:
$(".telephone").html(function () {;
return $(this).html().match(/[0-9]{3}/g).join('.');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="telephone">123456789</p>
I has use some jquery code, pls try this! hope this can help you! :)
$('.number').text(function () {
var txt = $(this).text();
return txt.replace(/\B(?=(?:\d{3})+(?!\d))/g, '.');
});
$(document).ready(function(){
$('.number').text(function () {
var txt = $(this).text();
return txt.replace(/\B(?=(?:\d{3})+(?!\d))/g, '.');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="number">123456789</p>
const convert= (str)=>{
let newStr=""
let pointer=0;
while(pointer < str.length){
newStr += str.charAt(pointer)
if(str.charAt(pointer) % 3 === 0 && pointer !== str.length-1){
newStr += "."
}
pointer++
}
console.log(newStr)
}
convert("123456789");
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/
How do I increment a string "A" to get "B" in Javascript?
function incrementChar(c)
{
}
You could try
var yourChar = 'A'
var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B'
So, in a function:
function incrementChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1)
}
Note that this goes in ASCII order, for example 'Z' -> '['. If you want Z to go back to A, try something slightly more complicated:
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
var index = alphabet.indexOf(c)
if (index == -1) return -1 // or whatever error value you want
return alphabet[index + 1 % alphabet.length]
}
var incrementString = function(string, count){
var newString = [];
for(var i = 0; i < string.length; i++){
newString[i] = String.fromCharCode(string[i].charCodeAt() + count);
}
newString = newString.join('');
console.log(newString);
return newString;
}
this function also can help you if you have a loop to go through
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.