I need to format a string for comparison purpose.
Lets say we have
Multiple Choice
I want to convert it to
multiplechoice
So white spaces removed, any special characters removed and lowercase.
I need to do this in SAPUI5 while comparing a value which I get from a model.
if (oCurrentQuestionModel.getProperty("/type") === "multiple choice")
How can I achieve this?
You can do it as:
var str = "Multiple Choice";
var strLower = str.toLowerCase();
strLower.replace(/\s/g, '');
Working demo.
The Regex
\s is the regex for "whitespace", and g is the "global" flag, meaning match all \s (whitespaces).
function cleaner(str) {
if (str) {
var strLower = str.toLowerCase();
return strLower.replace(/\W/g, '');
}
return false;
}
Related
Say, I have a text stored as:
var val1 = 'l-oreal';
I want to match val1 such that, it reads val1 and ignores hyphen (dash) in it. I want a regex that ignores special characters in a text. Is that possible?
I don't want to remove special character from the text. I want to ignore it.
You can match against the regex /[a-z]+/gi and then join by a space or any other character:
var testString = "any string l-orem";
var matcher = /[a-z]+/gi;
var matches = testString.match(matcher);
var result = matches.join('');
console.log(result);
This, of course, doesn't change your original string, and can be simply customized to your own needs.
You can either use ^ in order to select your special characters then replace it to an empty string '', as:
val1.replace(/([^a-zA-z0-9]+)/g, s0 => ''); // loreal
All except a-zA-Z-0-9 will be removed.
Updated post for scenario when:
The string must contain characters abc and ignore any special
characters
for this approach, you could make use of match to know if your string has any matches on your regex. If so, then you could use replace to switch special chars to empty string:
function strChecker(str) {
var response;
if(val1.match(/lorem/)) {
response = val1.replace(/([^a-zA-z0-9]+)/g, s0 => '');
}
return response;
}
strChecker('ha-ha?lorem') // returns hahalorem
strChecker('ha-ha?loram') // return undefined
var val1 = 'l-oreal';
var val2 = val1.replace(/\W/g,''); // remove any non-alphanumerics
console.log(val1); // still the same, not changed
console.log(val2); // only alphanumerics
I use
str.replace(/(^,)|(,$)/g, '')
to remove leading and trailing commas.
How can I extend it so I also remove two consecutive commas?
So ,some text,,more text, should become some text,more text?
One way would be to chain with
str.replace(/(^,)|(,$)/g, '').replace(/,,/g, ',')
but then ,some text,,,,more text, will become some text,,more text instead of some text,more text.
Since you appear to be using the str as a source for an array, you can replace all the .replace calls with:
var str = ",some text,,,,more text,";
var resultArray = str.split(',') // Just split the string.
.filter(function(item){ // Then filter out empty items
return item !== '';
});
console.log(resultArray)
No need to worry about leading, trailing or double comma's.
Remove the leading and trailing commas, and then replace multiple consecutive commas by single comma
str.replace(/^,|,$|(,)+/g, '$1');
,+ will match one or more comma, g-global flag to replace all occurrences of it.
var str = ',some text,,more text,';
str = str.replace(/^,|,$|(,)+/g, '$1');
console.log(str);
You may add an alternative branch and enclose it with a capturing group and then use a replace callback method where you can analyze the match groups and perform the replacement accordingly:
var s = ',some text,,,,more text,';
var res = s.replace(/^,|,$|(,+)/g, function(m,g1) {
return g1 ? ',' : '';
});
console.log(res);
To split with commas and get no empty entries in the resulting array, use a simple
console.log(',some text,,,,more text,'.split(',').filter(Boolean));
You could add a positive lookahead with another comma.
var str = ',some text,,more text,';
str = str.replace(/^,|,$|,(?=,)/g, '')
console.log(str);
What about one replace only like: ",some text,,,,more text,".replace(/(^,)|(,$)|,(?=,)/g, '');
[EDIT]
Note that lookbehinds don't work in javascript. so you can only use a lookahead like so.
I'm trying to do two things to clean the string, the first is to remove any space and replace it with a comma separator, the second is to remove any non-alphanumeric characters (other than the comma); I have the first part functional, but now I can't figure out how to remove the special characters as well:
$("#fancydiv").keyup(function(e) {
var str = this.value.replace(/(\w)[\s,]+(\w?)/g, '$1,$2');
if (str!=this.value) this.value = str;
});
'?no, special-characters!'.replace(/[^\w,]/g, '')
// => "no,specialcharacters"
[^\w,] will match match non-alphabet, non-digit, non-underscore character excluding a comma.
Try this:
var str = this.value.replace(/\s/g, ',').replace(/[^\w,]/g, '');
I am having some trouble with my regex in javascript.
I have the following code, that I think should match, but it doesn't.
var rgx = new RegExp("{\d+:(\d+)}");
if (rgx.test("{0:00000}") == true) {
alert("match");
}
else
{
alert("no match");
}
I am unsure if I should use test() here. I really want to catch the group, in my regex but exec() seems to give me the same result.
So what am I doing wrong?
The problem is that you need to escape the \ character in your regex:
var rgx = new RegExp("{\\d+:(\\d+)}");
Alternatively, you can use the literal syntax:
var rgx = /{\d+:(\d+)}/;
To capture the results, you should also use the .match function as opposed to test or exec. It will return null if it doesn't match and an array of at least one element if it does match.
There are multiple issues with the regex:
var rgx = new RegExp("{\d+:(\d+)}");
First (first noted by syazdani), you must string-escape the backslashes:
var rgx = new RegExp("{\\d+:(\\d+)}");
or better yet use a regex literal:
var rgx = /{\d+:(\d+)}/
Second, { and } have a special meaning in regex and should be escaped:
var rgx = /\{\d+:(\d+)\}/
Third, as noted by Ian, you might want to ensure the entire string is matched:
var rgx = /^\{\d+:(\d+)\}$/
RegExp#test returns a boolean true/false whether the string matches.
RegExp#exec returns an array holding the match and all captured groups if the string is matched, or null if the string is not matched:
var matches = /\{\d+:(\d+)\}/.exec("{0:000000}");
if(matches){
console.log(matches[1]); //logs "000000"
}
I want to remove all special characters except space from a string using JavaScript.
For example,
abc's test#s
should output as
abcs tests.
You should use the string replace function, with a single regex.
Assuming by special characters, you mean anything that's not letter, here is a solution:
const str = "abc's test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
You can do it specifying the characters you want to remove:
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g, '');
The first solution does not work for any UTF-8 alphabet. (It will cut text such as Привіт). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).
search all not (word characters || space):
str.replace(/[^\w ]/, '')
I don't know JavaScript, but isn't it possible using regex?
Something like [^\w\d\s] will match anything but digits, characters and whitespaces. It would be just a question to find the syntax in JavaScript.
I tried Seagul's very creative solution, but found it treated numbers also as special characters, which did not suit my needs. So here is my (failsafe) tweak of Seagul's solution...
//return true if char is a number
function isNumber (text) {
if(text) {
var reg = new RegExp('[0-9]+$');
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '')) {
result += text[i];
}
}
return result;
}
return '';
}
const str = "abc's#thy#^g&test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
Try to use this one
var result= stringToReplace.replace(/[^\w\s]/g, '')
[^] is for negation, \w for [a-zA-Z0-9_] word characters and \s for space,
/[]/g for global
With regular expression
let string = "!#This tool removes $special *characters* /other/ than! digits, characters and spaces!!!$";
var NewString= string.replace(/[^\w\s]/gi, '');
console.log(NewString);
Result //This tool removes special characters other than digits characters and spaces
Live Example : https://helpseotools.com/text-tools/remove-special-characters
dot (.) may not be considered special. I have added an OR condition to Mozfet's & Seagull's answer:
function isNumber (text) {
reg = new RegExp('[0-9]+$');
if(text) {
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '') || (lower[i].trim() === '.')) {
result += text[i];
}
}
return result;
}
return '';
}
Try this:
const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' #
Test27919<alerts#imimobile.com> #elseif_1 $(PR_CONTRACT_START_DATE) == '20-09-2019' #
Sender539<rama.sns#gmail.com> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #
AdestraSID<hello#imimobile.co> #else_1#Test27919<alerts#imimobile.com>#endif_1#`;
const replaceString = input.split('$(').join('->').split(')').join('<-');
console.log(replaceString.match(/(?<=->).*?(?=<-)/g));
Whose special characters you want to remove from a string, prepare a list of them and then user javascript replace function to remove all special characters.
var str = 'abc'de#;:sfjkewr47239847duifyh';
alert(str.replace("'","").replace("#","").replace(";","").replace(":",""));
or you can run loop for a whole string and compare single single character with the ASCII code and regenerate a new string.