Here is my array and string:
var array = new Array('üÜ', 'ıI', 'iİ', 'ğĞ', 'şŞ', 'çÇ');
var string = 'İSTANBUL, ÜSKÜDAR, Çarşamba'
I'd to replace every (for ü) to [üÜ]. I mean [üÜ]SK[üÜ]DAR. Can anyone help me?
You can use replace() method
string.replace(/ü|Ü/g, '[üÜ]')
For all matches,
array.forEach(function(key){
string = string.replace(new RegExp('['+ key +']', 'g'), '['+ key +']');
});
function replaceAll(source, search, replace, ignoreCase) {
//SCAPE SPECIAL CHARACTERES.
var search1 = search.toString().replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
//IGNORE CASE SENSIVITY.
var ignore = (ignoreCase) ? "gi" : "g";
var result = source.replace(new RegExp(search1, ignore), replace);
return result;
}
var array = new Array('üÜ', 'ıI', 'iİ', 'ğĞ', 'şŞ', 'çÇ');
for (var i=0; i < array.length; i++){
array[i] = replaceAll(array[i],"ü", "üÜ",true);
}
Related
function titleCase(str) {
var str1 = str.match(/\S+\s*/g);
var str2;
for(var i = 0; i < str1.length; i++){
str2 = str1[i].toLowerCase().replace(str1[i].charAt(0), str1[i].charAt(0).toUpperCase());
}
return str2.join(' ');
}
titleCase("I'm a little tea pot");
What's wrong with my code? str2.join is not a function
Easiest way to go about this is to split the string on every space, then set the first letter of each element in the array to the capitalized version of the letter and join it back.
What you are doing is assigning the value of the result to str2, having a string type rather than an array, that is why join is not working for you.
function titleCase(str) {
const words = str.split(' ');
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
return words.join(' ');
}
A slightly different variant with some ES6 favor to it:
const titleCase = str => {
const result = [];
for (const word of str.split(' ')) {
result.push(word[0].toUpperCase() + word.slice(1));
}
return result.join(' ');
};
If you want to ensure space characters such as tabs, newlines etc. work, you can split using your regex or replace all whitespace characters with spaces as a first step, e.g.:
const words = str.replace(/\s/g, ' ').split(' ').filter(word => word !== '');
function titleCase(str) {
var str1 = str.match(/\S+\s*/g);
var str2 = [];
for(var i = 0; i < str1.length; i++){
str2[i] = str1[i].replace(str1[i].charAt(0), str1[i].charAt(0).toUpperCase());
}
return str2.join(' ');
}
titleCase("I'm a little tea pot");
This is a simple solution to your problem. However, there are many ways to get the same result this is one of them.
function capitalize(str) {
let str2 = str[0].toUpperCase();
return str.replace(str[0], str2);
}
The code below doesn't work why?
function titleCase(str){
var newStr = str.split(" "); //split string turn it into seperated words[]
var resutl;
for(vari=0; i < newStr.length; i++){ //iterate all words
var result = newStr[i].charAt(0).toUpperCase +
// find first letter and turn it into capital
newStr[i].subString(1).toLowerCase();
}
return result.join(" ");
}
result in your code is a string, not an array. you cannot join a string.
each iteration of the loop you are replacing the variable result with a new word. you need to initialize a result array [] and push each result onto the array, then join the array after the loop has completed.
The result needs to be an array and also you have some typos in your code, e.g. missing ()
function titleCase(str) {
var newStr = str.split(" ");
var result = [];
for (var i = 0; i < newStr.length; i++) {
result.push(newStr[i].charAt(0).toUpperCase() + newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
var str = 'hELLO wORLD';
document.write(titleCase(str));
Try using regular expression
var data = "The mission is to turn each word's first letter into capital";
data = data.replace(/ (.)/g,function(w){return w.toUpperCase()});
drawback :this will not capitalize the first character.
Explode the string on spaces and iterate it with the function below:
function ucfirst(str) {
str += ''; // make sure str is really a string
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
You may try this :
function titleCase(str){
var newStr = str.split(" ");
var result = [];
for(var i=0; i < newStr.length; i++){
result.push(newStr[i].charAt(0).toUpperCase() +
newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
Another Approach:
function titleCase(str){
var words = str.split(" ");
return words.map(function(word){
return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
}).join(" ");
}
I'm looking for a regex that will remove all characters that have been repeated in a string. I already solved this using a loop. Just wondering if there is a regex that can do the same.
this is what i have so far:
function onlyUnique(str) {
var re = /(.)(?=.*\1)/g
return str.replace(re, '');
}
This string:
"rc iauauc!gcusa_usdiscgaesracg"
should end up as this:
" !_de"
You can use Array#filter with Array#indexOf and Array#lastIndexOf to check if the element is repeated.
var str = "rc iauauc!gcusa_usdiscgaesracg";
// Split to get array
var arr = str.split('');
// Filter splitted array
str = arr.filter(function (e) {
// If index and lastIndex are equal, the element is not repeated
return arr.indexOf(e) === arr.lastIndexOf(e);
}).join(''); // Join to get string from array
console.log(str);
document.write(str);
well, no idea if regex can do that, but you could work it out using for loop, like:
function unikChars(str) {
store = [];
for (var a = 0, len = str.length; a < len; a++) {
var ch = str.charAt(a);
if (str.indexOf(ch) == a && str.indexOf(ch, a + 1) == -1) {
store.push(ch);
}
}
return store.join("");
}
var str = 'rc iauauc!gcusa_usdiscgaesracg';
console.log(unikChars(str)); //gives !_de
Demo:: jsFiddle
Your regex searches pairs of duplicated characters and only removes the first one. Therefore, the latest duplicate won't be removed.
To address this problem, you should remove all duplicates simultaneously, but I don't think you can do this with a single replace.
Instead, I would build a map which counts the occurrences of each character, and then iterate the string again, pushing the characters that appeared only once to a new string:
function onlyUnique(str) {
var map = Object.create(null);
for(var i=0; i<str.length; ++i)
map[str[i]] = (map[str[i]] || 0) + 1;
var chars = [];
for(var i=0; i<str.length; ++i)
if(map[str[i]] === 1)
chars.push(str[i]);
return chars.join('');
}
Unlike indexOf, searches in the hash map are constant on average. So the cost of a call with a string of n characters will be n.
If you want to do it with a regex, you can use your own regex with a callback function inside a replace.
var re = /(.)(?=.*\1)/g;
var str = 'rc iauauc!gcusa_usdiscgaesracg';
var result = str;
str.replace(re, function(m, g1) {
result = result.replace(RegExp(g1.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), '');
});
document.getElementById("r").innerHTML = "'" + result + "'";
<div id="r"/>
The idea is: get the duplicated character, and remove it from the input string. Note that escaping is necessary if the character might be a special regex metacharacter (thus, g1.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") is used).
Another idea belongs to Washington Guedes in his deleted answer, I just add my own implementation here (with removing duplicate symbols from the character class and escaping special regex chars):
var s = "rc iauauc!gcusa_u]sdiscgaesracg]";
var delimiters= '[' + s.match(/(.)(?=.*\1)/g).filter(function(value, index, self) { // find all repeating chars
return self.indexOf(value) === index; // get unique values only
}).join('').replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ']'; // escape special chars
var regex = new RegExp(delimiters, 'g'); // build the global regex from the delimiters
var result = s.replace(regex, ''); // obtain the result
document.getElementById("r2").innerHTML = "'" + result + "'";
<div id="r2"/>
NOTE: if you want to support newline symbols as well, replace . with [^] or [\s\S] inside the regex pattern.
function onlyUnique(str) {
// match the characters you want to remove
var match = str.match(/(.)(?=.*\1)/g);
if (match) {
// build your regex pattern
match = '[' + match.join('') + ']';
}
// if string is already unique return the string
else {
return str
}
// create a regex with the characters you want to remove
var re = new RegExp(match, 'g');
return str.replace(re, '');
}
I am writing a function to make slug from input.
var vslug = function (str) {
str = str.replace(/^\s+|\s+$/g, '');
str = str.toLowerCase();
var vregex = /(?:\.([^.]+))?$/;
var filename = str.replace(vregex.exec(str)[0],'');
var extension = vregex.exec(str)[1];
var from = "àáäâèéëêìíïîıòóöôùúüûñçşğ·/,:;";
var to = "aaaaeeeeiiiiioooouuuuncsg_____";
for (var i = 0; i < from.length; i++) {
console.log('before ' + str);
str = filename.replace(new RegExp(from[i], 'g'), to[i]);
console.log('after ' + str);
}
str = str.replace(/[^a-z0-9 _-]/g, '')
.replace(/\s+/g, '_')
.replace(/-+/g, '_');
if (typeof extension !== "undefined") {
return str+'.'+extension;
} else {
return str;
}
};
I can't make this part - I gone blind. Any help is appreciated..
var from = "àáäâèéëêìíïîıòóöôùúüûñçşğ·/,:;";
var to = "aaaaeeeeiiiiioooouuuuncsg_____";
for (var i = 0; i < from.length; i++) {
console.log('before ' + str);
str = filename.replace(new RegExp(from[i], 'g'), to[i]);
console.log('after ' + str);
}
filename is not changed - the variable names the same string, and the string cannot be modified. As such, each loop starts working on the original string again when it uses filename.replace...
Instead, eliminate filename (or integrate it fully) and use str = str.replace..
str = str.replace(vregex.exec(str)[0],'');
for (var i = 0; i < from.length; i++) {
str = str.replace(new RegExp(from[i], 'g'), to[i]);
// ^-- next loop gets new value
}
(Also, this could be handled with a replacement function and a map instead of n-loops and there might be a Unicode library for JavaScript available..)
An approach using a map and a replacement function might look like:
// Specify map somewhere reusable; can be built from paired arrays for simplicity.
var replacements = {"à":"a", "á":"a", .. ";":"_"}
// Object.keys is ES5, shim as needed. e.g. result: [à;á..]
var alternation = "[" + Object.keys(replacements).join("") + "]"
// This regex will match all characters we are trying to match.
var regex = new Regex(alternation, "g")
str = str.replace(regex, function (m) {
var r = replacements[m]
return r || m
})
See String.replace(regex, function)
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (var i = 0; i < str.length; i++) {
var index = alphabet.indexOf(str[i])
if (/[a-zA-Z]/.test(str[i])) {
str = str.replace(str[i], alphabet.charAt(index + 1));
}
if (/[aeiou]/.test(str[i])) {
str = str.replace(str[i], alphabet.charAt(index + 26));
}
}
return str;
}
When I call LetterChanges("hello"), it returns 'Ifmmp' which is correct, but when "sent" is passed it returns 'ufOt' instead of 'tfOu'. Why is that?
str.replace() replaces the first occurrence of the match in the string with the replacement. LetterChanges("sent") does the following:
i = 0 : str.replace("s", "t"), now str = "tent"
i = 1 : str.replace("e", "f"), now str = "tfnt"
i = 2 : str.replace("n", "o"), now str = "tfot", then
str.replace("o", "O"), now str = "tfOt"
i = 3 : str.replace("t", "u"), now str = "ufOt"
return str
There are several issues. The main one is that you could inadvertently change the same letter several times.
Let's see what happens to the s in sent. You first change it to t. However, when it comes to changing the final letter, which is also t, you change the first letter again, this time from t to u.
Another, smaller, issue is the handling of the letter z.
Finally, your indexing in the second if is off by one: d becomes D and not E.
You can use String.replace to avoid that:
function LetterChanges(str) {
return str.replace(/[a-zA-Z]/g, function(c){
return String.fromCharCode(c.charCodeAt(0)+1);
}).replace(/[aeiou]/g, function(c){
return c.toUpperCase();
});
}
But there is still a bug: LetterChanges('Zebra') will return '[fcsb'. I assume that is not your intention. You will have to handle the shift.
Try this one:
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = '';
var temp;
for (var i = 0; i < str.length; i++) {
var index = alphabet.indexOf(str[i])
if (/[a-zA-Z]/.test(str[i])) {
//str = str.replace(str[i], alphabet.charAt(index + 1));
temp= alphabet.charAt(index + 1);
index = index+1;
}
else if(str[i] == ' '){
temp = ' ';
}
if (/[aeiou]/.test(temp)) {
temp = alphabet.charAt(index + 26);
}
result += temp;
}
return result;
}
var str = 'bcd12';
str = str.replace(/[a-z]/gi, function(char) { //call replace method
char = String.fromCharCode(char.charCodeAt(0)+1);//increment ascii code of char variable by 1 .FromCharCode() method will convert Unicode values into character
if (char=='{' || char=='[') char = 'a'; //if char values goes to "[" or"{" on incrementing by one as "[ ascii value is 91 just after Z" and "{ ascii value is 123 just after "z" so assign "a" to char variable..
if (/[aeiuo]/.test(char)) char = char.toUpperCase();//convert vowels to uppercase
return char;
});
console.log(str);
Check this code sample. There is no bug in it. Not pretty straight forward but Works like a charm. Cheers!
function LetterChanges(str) {
var temp = str;
var tempArr = temp.split("");//Split the input to convert it to an Array
tempArr.forEach(changeLetter);/*Not many use this but this is the referred way of using loops in javascript*/
str = tempArr.join("");
// code goes here
return str;
}
function changeLetter(ele,index,arr) {
var lowerLetters ="abcdefghijklmnopqrstuvwxyza";
var upperLetters ="ABCDEFGHIJKLMNOPQRSTUVWXYZA";
var lowLetterArr = lowerLetters.split("");
var upLetterArr = upperLetters.split("");
var i =0;
for(i;i<lowLetterArr.length;i++){
if(arr[index] === lowLetterArr[i]){
arr[index] = lowLetterArr[i+1];
arr[index]=arr[index].replace(/[aeiou]/g,arr[index].toUpperCase());
return false;
}
if(arr[index] === upLetterArr[i]){
arr[index] = upLetterArr[i+1];
arr[index]=arr[index].replace(/[aeiou]/g,arr[index].toUpperCase());
return false;
}
}
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
LetterChanges(readline());