There is any way to make a regex to replace symbols + blank space?
Im using:
const cleanMask = (value) => {
const output = value.replace(/[_()-]/g, "").trim();
return output;
}
let result = cleanMask('this (contains parens) and_underscore, and-dash')
console.log(result)
Its it right?
Your current code will replace all occurrences of characters _, (, ) and - with an empty string and then trim() whitespace from the beginning and end of the result.
If you want to remove ALL whitespace, you can use the whitespace character class \s instead of trim() like this:
const output = value.replace(/[_()-\s]/g, "");
Related
urlEncode = function(text) {
let str = text.split(' ').join('%20');
return str;
};
The above is working but If a string has a space in the beginning or end it should not replace %20 .The above is replacing every space .I tried using loops ..
for(let i = 1 ;i < text.length-1;i++){
if(text[i]===''){
text[i]='%20';
}
}
return text;
this one is returning the original text with no change.
A regular expression to match a space not at the beginning nor end of the string would work.
const urlEncode = text => text.replace(/(?!^) (?!$)/g, '%20');
(?!^) - not at the beginning
(?!$) - not at the end
Another method would be to turn the text string into an array so that assignment to its indicies using your second snippet would work. Replace the indicies as needed, then join into a string again and return.
or, you can test another
const urlEncode = text => text.replace(/[^\s]\s[^\s$]/g, '%20')
I have an input field where the user is only allowed to use letters, spaces and commas.
I've created this here so far:
splitStr = splitStr.split(' ').join(', ');
splitStr = splitStr.split(',').join(', ');
splitStr = splitStr.split(';').join(', ');
splitStr = splitStr.split('-').join(', ');
splitStr = splitStr.split('_').join(', ');
splitStr = splitStr.split('/').join(', ');
splitStr = splitStr.split('#').join(', ');
$("imgTags").value = splitStr;
// removes duplicate spaces
splitStr = splitStr.replace(/ +(?= )/g,'');
// removes duplicate commas
splitStr = splitStr.replace(/,+/g,',');
// missing: remove ', ' duplicates
So this code above makes it so that the users input is always converted to a comma space and on the bottom of the code I'm removing artifacts that can happen, like duplicate commas or duplicate spaces.
In the first like you can see that I'm also replacing any space with comma space.. this gives me an artifact of , , , , , , , , , , , , , , , this means I need also to replaces any comma space comma space with just a single comma space, so I've tried to do this but I never get the the desired result.
How can I replace regex for space comma duplicates?
This: , , , , , , needs to become this , e.g. comma space comma space comma space needs to be just comma space.
very easy, something like this
str.replace(/(, )+/g, ", ")
or even in the very beginning
str.replace(/[-_;, ]+/g, ", ")
Split string by non-letters and join with commas:
str.split(/[^A-Za-z]/).join(',')
replace duplicate commas:
str.replace(/,+/g,',');
replace comma with comma space
str.replace(/,/g,', ');
You could do all those replacements in one go using a repeated character class and replace the matches with a comma and a space.
Because the character class is repeated, it will match consecutive matches and use only a single replacement.
[ ,;_\/#-]+
Regex demo
const regex = /[ ,;_\/#-]+/g;
const str = `test,,,,,test; test-test/test`;
const subst = `, `;
const result = str.replace(regex, subst);
console.log(result);
If you don't want to replace when the characters are at the start or end of the line, you might use a callback function for the replacement:
let pattern = /(?:^[ ,;_\/#-]+|[ ,;_\/#-]+$)|([ ,;_\/#-]+)/g;
let str = "/#,test,,,test; test-test/test,#/";
str = str.replace(pattern, function(m, g1) {
if (g1 !== undefined) {
return ', ';
}
return m;
});
console.log(str);
I want to remove all special characters from string and add only one "-"(hyphen) in the place.
Consider below example
var string = 'Lorem%^$&*&^Ipsum#^is#!^&simply!dummy text.'
So, from the above string, if there is a continuous number of special characters then I want to remove all of them and add only one "-" or if there is a single or double special character then also that should be replaced by "-"
Result should be like this
Lorem-Ipsum-is-simply-dummy text-
I have tried below, but no luck
var newString = sourceString.replace(/[\. ,:-]+/g, "-");
You could use .replace to replace all non-alphabetical character substrings with -:
const input = 'Lorem%^$&*&^Ipsum#^is#!^&simply!dummy text.';
const output = input.replace(/[^\w\s]+/gi, '-');
console.log(output);
If you want to permit numbers too:
const input = 'Lorem123%^$&*&^654Ipsum#^is#!^&simply!dummy text.';
const output = input.replace(/[^\w\s\d]+/gi, '-');
console.log(output);
I am having trouble below javaScript problem.
Question:
You have been given a string s, which is supposed to be a sentence. However, someone forgot to put spaces between the different words, and for some reason they capitalized the first letter of every word. Return the sentence after making the following amendments:
Put a single space between the words.
Convert the uppercase letters to lowercase.
Example
"CodefightsIsAwesome", the output should be "codefights is awesome";
"Hello", the output should be "hello".
My current code is:
Right now, my second for-loop just manually slices the parts from the string.
How can I make this dynamic and insert "space" in front of the Capital String?
You can use String.prototype.match() with RegExp /[A-Z][^A-Z]*/g to match A-Z followed by one or more characters which are not A-Z, or character at end of string; chain Array.prototype.map() to call .toLowerCase() on matched words, .join() with parameter " " to include space character between matches at resulting string.
var str = "CodefightsIsAwesome";
var res = str.match(/[A-Z][^A-Z]*/g).map(word => word.toLowerCase()).join(" ");
console.log(res);
Alternatively, as suggested by #FissureKing, you can use String.prototype.repalce() with .trim() and .toLowerCase() chained
var str = "CodefightsIsAwesome";
var res = str.replace(/[A-Z][^A-Z]*/g, word => word + ' ').trim().toLowerCase();
console.log(res);
Rather than coding a loop, I'd do it in one line with a (reasonably) simple string replacement:
function amendTheSentence(s) {
return s.replace(/[A-Z]/g, function(m) { return " " + m.toLowerCase() })
.replace(/^ /, "");
}
console.log(amendTheSentence("CodefightsIsAwesome"));
console.log(amendTheSentence("noCapitalOnFirstWord"));
console.log(amendTheSentence("ThereIsNobodyCrazierThanI"));
That is, match any uppercase letter with the regular expression /[A-Z]/, replace the matched letter with a space plus that letter in lowercase, then remove any space that was added at the start of the string.
Further reading:
String .replace() method
Regular expressions
We can loop through once.
The below assumes the very first character should always be capitalized in our return array. If that is not true, simply remove the first if block from below.
For each character after that, we check to see if it is capitalized. If so, we add it to our return array, prefaced with a space. If not, we add it as-is into our array.
Finally, we join the array back into a string and return it.
const sentence = "CodefightsIsAwesome";
const amend = function(s) {
ret = [];
for (let i = 0; i < s.length; i++) {
const char = s[i];
if (i === 0) {
ret.push(char.toUpperCase());
} else if (char.toUpperCase() === char) {
ret.push(` ${char.toLowerCase()}`);
} else {
ret.push(char);
}
}
return ret.join('');
};
console.log(amend(sentence));
I'm trying to split text the following like on spaces:
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}"
but I want it to ignore the spaces within parentheses. This should produce an array with:
var words = ["Text", "(what is)|what's", "a", "story|fable" "called|named|about", "{Search}|{Title}"];
I know this should involve some sort of regex with line.match(). Bonus points if the regex removes the parentheses. I know that word.replace() would get rid of them in a subsequent step.
Use the following approach with specific regex pattern(based on negative lookahead assertion):
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}",
words = line.split(/(?!\(.*)\s(?![^(]*?\))/g);
console.log(words);
(?!\(.*) ensures that a separator \s is not preceded by brace ((including attendant characters)
(?![^(]*?\)) ensures that a separator \s is not followed by brace )(including attendant characters)
Not a single regexp but does the job. Removes the parentheses and splits the text by spaces.
var words = line.replace(/[\(\)]/g,'').split(" ");
One approach which is useful in some cases is to replace spaces inside parens with a placeholder, then split, then unreplace:
var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}";
var result = line.replace(/\((.*?)\)/g, m => m.replace(' ', 'SPACE'))
.split(' ')
.map(x => x.replace(/SPACE/g, ' '));
console.log(result);