I need to replace the = to == using the JavaScript on the condition it should not replace if is already as
==
>=
<=
=>
=<
Can anyone help me in this with the explanation. I am trying like below but it was replacing all.
text = text.replace(/=/, "==");
Input :
Premium UserId=5||Premium UserId>=2
Output Needed:
Premium UserId==5||Premium UserId>=2
Use the following regex:
var str = 'Premium UserId=5||Premium = UserId>=2',
re = /([^=><])=([^=><]*?)/g;
console.log(str.replace(re, "$1==$2"));
You should use this opportunity to learn about regular expression lookaround. Unfortunately, while JavaScript supports lookahead, it doesn't support lookbehind. Therefore, while the regex /=(?![>=<])/ will successfully avoid the following matches: =< and =>, it'll still match everything else.
However, there are ways to simulate lookbehind in Javascript. You can use the following code snippet to achieve what you're trying to do:
var text = 'Premium UserId=5||Premium UserId>=2';
text = text.replace(/([>=<])?=(?![>=<])/g, function($0, $1) {
return $1 ? $0 : $0 + '=';
});
console.log(text)
maybe something like this? (will not match the very beginning or end of text...)
text=text.replace(/([^=><])=([^=><])/g, function (match,p1,p2){ return p1+"=="+p2; });
var text = "Premium UserId=5||Premium UserId>=2";
text=text.replace(/([^=><])=([^=><])/g, function (match,p1,p2){ return p1+"=="+p2; });
console.log(text)
Try this approach
var input = "Premium UserId=5||Premium UserId>=2";
var regex = new RegExp( "(?:[0-9a-z\s])=(?![<>])", "gi" );
var output = input.replace( regex , function(match){ return match.charAt(0) + "==" } );
console.log(output);
console.log("Premium UserId =5||Premium UserId>=2".replace( /(?:[0-9a-z\s])=(?![<>])/gi, function(match){ return match.charAt(0) + "==" } ));
console.log("Premium UserId =>5||Premium UserId>=2".replace( /(?:[0-9a-z\s])=(?![<>])/gi, function(match){ return match.charAt(0) + "==" } ));
var re = /(([^<>=])(={1,1})([^<>=]))/g
var tests = [
{in: 'Premium UserId=5||Premium UserId>=2', out: 'Premium UserId==5||Premium UserId>=2'},
{in: 'if (UserId == 5)', out: 'if (UserId == 5)'}
]
tests.forEach(function(test, idx){
var result = test.in.replace(re, '$2==$4') === test.out
console.log('test', idx, result)
})
Related
I want to test the URL http://example.com in a browser window for an empty search string, i.e http://example.com/search/?s=, but not match anything like /search/?s=withsearchterms that has any search terms after the /search/?s=, and then use an if statement and .addClass to display a div that warns that no search terms were entered.
I'm trying to use Javascript and g.test like below; the RegEx pattern is valid, according to several RegEx testers. But no luck:
var href = window.location.href;
var contains = /[\/?s=]+/g.test(href);
if (contains) {
$("#no-search-terms").addClass("display-block");
}
Is my RegEx wrong? Is my use of test wrong?
Edit 11/29/2020
This work, thanks to Heo:
var search = window.location.href;
var regex = /(?<=\/\?s=).*$/
var result=regex.exec( search )
if (result && result[0]=='') {
alert("The search terms are empty.");
} else {
alert("The search terms are not empty or no matched.");
}
But miknik's answer is much simpler with no need for regex. Works on Chrome 87, Firefox 83 and Safari 14:
const queries = new URLSearchParams(window.location.search)
if (queries.has("s") && queries.get("s").length == 0){
alert("The search terms are empty.");
}
You can test if end of string contains /?s=:
var url1 = 'https://example.com/?s=';
var url2 = 'https://example.com/?s=withsearchterms';
var regex = /\/\?s=$/;
console.log(url1 + ' ==> ' + regex.test(url1));
console.log(url2 + ' ==> ' + regex.test(url2));
Output:
https://example.com/?s= ==> true
https://example.com/?s=withsearchterms ==> false
Explanation:
\/\?s= - expect /?s=
$ - trailing $ anchors the regex at the end, e.g. preceding text must occur at the end
thus, the test returns true if the url has no search term (you can reverse your if test)
No need for regex here, something like this should work fine in modern browsers:
const queries = new URLSearchParams(window.location.search)
if (queries.has("s") && queries.get("s").length == 0){
// do stuff
}
Another alternative that (mostly) avoids regular expressions:
function isEmptySearch(urlString) {
const url = new URL(urlString);
const urlParams = url.search.replace(/^\?/, '').split('&').reduce( (acc, cur) => {
const param = cur.split('=');
acc[param[0]] = param[1];
return acc;
}, {});
return !urlParams.s;
}
const testUrls = [
"http://example.com/search/",
"http://example.com/search/?s=",
"http://example.com/search/?s=&foo=bar&baz",
"http://example.com/search/?s=hello&foo=bar&baz"
];
testUrls.forEach( url => console.log(`${url}: empty search = ${isEmptySearch(url)}`) );
I think I prefer the regex option presented earlier by Peter Thoeny as it's less verbose, but this version might be of interest.
If You want to use REGEX, you could use exec() instead of test() because the test function isn't good at the case.
Try this:
//URL-input
var href1 = 'http://example.com/?s='
var href2 = 'http://example.com/?s=xx'
var href3 = 'http://example.com/'
function alertsSearchString( href ){
var regex = /(?<=\/\?s=).*$/
var Container= regex.exec( href )
if ( Container!=null && Container[0]=='' )
alert( 'The search string is an empty string!' )
else if (Container!=null)
alert( 'The search string: ' + Container[0] )
else
alert( "The Container is "
+ Container
+", because input URL isn't matched the \nREGEX : "
+ regex.toString() )
}
//alerts-output
alertsSearchString( href1 )
alertsSearchString( href2 )
alertsSearchString( href3 )
Output:
First Alert : The search string is an empty string!
SecondAlert : The search string: xx
Third Alert : The Container is null because input URL isn't matched the
REGEX : /(?<=\/\?s=).*$/
Detail:
Regex expression: (?<=\/\?s=).*$
(?<=\/\?s=) use lookbehind to check and skip /?s=.
.* match zero to more characters after /?s=.
$ preceding text must occur at the end.
See regex-demo
The source below is an edited from your example Edit 11/22/2020 using exec()
var search = 'http://example.com/search/?s='
var regex = /(?<=\/\?s=).*$/
var result=regex.exec( search )
if (result && result[0]=='') {
alert("The search terms are empty.");
} else {
alert("The search terms are not empty or no matched.");
}
Forget regex, nodejs URL is your friend. https://nodejs.org/dist/latest-v14.x/docs/api/url.html#url_new_url_input_base
for legacy nodejs versions you can use url.parse and querystring.parse
const { URL } = require('url');
const url1 = new URL('https://example.com/?s=');
const url2 = new URL('https://example.com/?s=withsearchterms');
function hasEmptyQuery(u) {
return [...u.searchParams]
.some(([key, value]) => value.length === 0);
}
console.log(hasEmptyQuery(url1));
// true
console.log(hasEmptyQuery(url2));
// false
I want to create a regex with following logic:
1., If string contains T replace it with space
2., If string contains Z remove Z
I wrote two regex already, but I can't combine them:
string.replace(/\T/g,' ') && string.replace(/\Z/g,'');
EDIT: I want the regex code to be shorter
Doesn't seem this even needs regex. Just 2 chained replacements would do.
var str = '[T] and [Z] but not [T] and [Z]';
var result = str.replace('T',' ').replace('Z','');
console.log(result);
However, a simple replace only replaces the first occurence.
To replace all, regex still comes in handy. By making use of the global g flag.
Note that the characters aren't escaped with \. There's no need.
var str = '[T] and [Z] and another [T] and [Z]';
var result = str.replace(/T/g,' ').replace(/Z/g,'');
console.log(result);
// By using regex we could also ignore lower/upper-case. (the i flag)
// Also, if more than 1 letter needs replacement, a character class [] makes it simple.
var str2 = '(t) or (â) and (z) or (â). But also uppercase (T) or (Z)';
var result2 = str2.replace(/[tâ]/gi,' ').replace(/[zâ]/gi,'');
console.log(result2);
But if the intention is to process really big strings, and performance matters?
Then I found out in another challenge that using an unnamed callback function inside 1 regex replace can prove to be faster. When compared to using 2 regex replaces.
Probably because if it's only 1 regex then it only has to process the huge string once.
Example snippet:
console.time('creating big string');
var bigstring = 'TZ-'.repeat(2000000);
console.timeEnd('creating big string');
console.log('bigstring length: '+bigstring.length);
console.time('double replace big string');
var result1 = bigstring.replace(/[t]/gi,'X').replace(/[z]/gi,'Y');
console.timeEnd('double replace big string');
console.time('single replace big string');
var result2 = bigstring.replace(/([t])|([z])/gi, function(m, c1, c2){
if(c1) return 'X'; // if capture group 1 has something
return 'Y';
});
console.timeEnd('single replace big string');
var smallstring = 'TZ-'.repeat(5000);
console.log('smallstring length: '+smallstring.length);
console.time('double replace small string');
var result3 = smallstring.replace(/T/g,'X').replace(/Z/g,'Y');
console.timeEnd('double replace small string');
console.time('single replace small string');
var result4 = smallstring.replace(/(T)|(Z)/g, function(m, c1, c2){
if(c1) return 'X';
return 'Y';
});
console.timeEnd('single replace small string');
Do you look for something like this?
ES6
var key = {
'T': ' ',
'Z': ''
}
"ATAZATA".replace(/[TZ]/g, (char) => key[char] || '');
Vanilla
"ATAZATA".replace(/[TZ]/g,function (char) {return key[char] || ''});
or
"ATAZATA".replace(/[TZ]/g,function (char) {return char==='T'?' ':''});
you can capture both and then decide what to do in the callback:
string.replace(/[TZ]/g,(m => m === 'T' ? '' : ' '));
var string = 'AZorro Tab'
var res = string.replace(/[TZ]/g,(m => m === 'T' ? '' : ' '));
console.log(res)
-- edit --
Using a dict substitution you can also do:
var string = 'AZorro Tab'
var dict = { T : '', Z : ' '}
var re = new RegExp(`[${ Object.keys(dict).join('') }]`,'g')
var res = string.replace(re,(m => dict[m] ) )
console.log(res)
Second Update
I have developed the following function to use in production, perhaps it can help someone else. It's basically a loop of the native's replaceAll Javascript function, it does not make use of regex:
function replaceMultiple(text, characters){
for (const [i, each] of characters.entries()) {
const previousChar = Object.keys(each);
const newChar = Object.values(each);
text = text.replaceAll(previousChar, newChar);
}
return text
}
Usage is very simple:
const text = '#Please send_an_information_pack_to_the_following_address:';
const characters = [
{
"#":""
},
{
"_":" "
},
]
const result = replaceMultiple(text, characters);
console.log(result); //'Please send an information pack to the following address:'
Update
You can now use replaceAll natively.
Outdated Answer
Here is another version using String Prototype. Enjoy!
String.prototype.replaceAll = function(obj) {
let finalString = '';
let word = this;
for (let each of word){
for (const o in obj){
const value = obj[o];
if (each == o){
each = value;
}
}
finalString += each;
}
return finalString;
};
'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"
I'm aware of the CSS attribute text-transform: capitalize but can anyone help me with replicating this using Javascript?
I would like to pass an argument to my function which will return the string with the first letter of each word capitalized.
I've got this far but I'm stuck trying to break my array of strings in to chunks:
function upper(x){
x = x.split(" ");
// this function should return chunks but when called I'm getting undefined
Array.prototype.chunk = function ( n ) {
return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
};
x = x.chunk;
}
upper("chimpanzees like cigars")
after the chunk I'm guessing I need to again split each chunk in to the first character and the remaining characters, use .toUpperCase() on the first character, join it back up with the remaining and then join up the chunks again in to a string?
Is there a simpler method for doing this?
I came up with a solution for both a single word and also for an array of words. It will also ensure that all other letters are lowercase for good measure. I used the Airbnb style guide as well. I hope this helps!
const mixedArr = ['foo', 'bAr', 'Bas', 'toTESmaGoaTs'];
const word = 'taMpa';
function capitalizeOne(str) {
return str.charAt(0).toUpperCase().concat(str.slice(1).toLowerCase());
}
function capitalizeMany(args) {
return args.map(e => {
return e.charAt(0).toUpperCase().concat(e.slice(1).toLowerCase());
});
};
const cappedSingle = capitalizeOne(word);
const cappedMany = capitalizeMany(mixedArr);
console.log(cappedSingle);
console.log(cappedMany);
The map function is perfect for this.
w[0].toUpperCase() : Use this to capitalize the first letter of each word
w.slice(1): Return the string from the second character on
EDGE Case
If the user doesn't enter a string, the map function will not work and an error will be raised. This can be guarded against by checking if the user actually entered something.
var userInput = prompt("Enter a string");
var capitalizedString = userInput == "" ? "Invalid String" :
userInput.split(/\s+/).map(w => w[0].toUpperCase() + w.slice(1)).join(' ');
console.log(capitalizedString);
You can use the following solution which doesn't use regex.
function capitalize(str=''){
return str.trim().split('')
.map((char,i) => i === 0 ? char.toUpperCase() : char )
.reduce((final,char)=> final += char, '' )
}
capitalize(' hello') // Hello
"abcd efg ijk lmn".replace(/\b(.)/g, (m => m.toUpperCase())) // Abcd Efg Ijk Lmn
You may want to try a regex approach:
function upperCaseFirst(value) {
var regex = /(\b[a-z](?!\s))/g;
return value ? value.replace(regex, function (v) {
return v.toUpperCase();
}) : '';
}
This will grab the first letter of every word on a sentence and capitalize it, but if you only want the first letter of the sentence, you can just remove the g modifier at the end of the regex declaration.
or you could just iterate the string and do the job:
function capitalize(lowerStr){
var result = "";
var isSpacePrevious = false;
for (var i=0; i<lowerStr.length; i++){
if (i== 0 || isSpacePrevious){
result += lowerStr[i].toUpperCase();
isSpacePrevious = false;
continue;
}
if (lowerStr[i] === ' '){
isSpacePrevious = true;
}
result += lowerStr[i];
}
return result;
}
Given a string
'1.2.3.4.5'
I would like to get this output
'1.2345'
(In case there are no dots in the string, the string should be returned unchanged.)
I wrote this
function process( input ) {
var index = input.indexOf( '.' );
if ( index > -1 ) {
input = input.substr( 0, index + 1 ) +
input.slice( index ).replace( /\./g, '' );
}
return input;
}
Live demo: http://jsfiddle.net/EDTNK/1/
It works but I was hoping for a slightly more elegant solution...
There is a pretty short solution (assuming input is your string):
var output = input.split('.');
output = output.shift() + '.' + output.join('');
If input is "1.2.3.4", then output will be equal to "1.234".
See this jsfiddle for a proof. Of course you can enclose it in a function, if you find it necessary.
EDIT:
Taking into account your additional requirement (to not modify the output if there is no dot found), the solution could look like this:
var output = input.split('.');
output = output.shift() + (output.length ? '.' + output.join('') : '');
which will leave eg. "1234" (no dot found) unchanged. See this jsfiddle for updated code.
It would be a lot easier with reg exp if browsers supported look behinds.
One way with a regular expression:
function process( str ) {
return str.replace( /^([^.]*\.)(.*)$/, function ( a, b, c ) {
return b + c.replace( /\./g, '' );
});
}
You can try something like this:
str = str.replace(/\./,"#").replace(/\./g,"").replace(/#/,".");
But you have to be sure that the character # is not used in the string; or replace it accordingly.
Or this, without the above limitation:
str = str.replace(/^(.*?\.)(.*)$/, function($0, $1, $2) {
return $1 + $2.replace(/\./g,"");
});
You could also do something like this, i also don't know if this is "simpler", but it uses just indexOf, replace and substr.
var str = "7.8.9.2.3";
var strBak = str;
var firstDot = str.indexOf(".");
str = str.replace(/\./g,"");
str = str.substr(0,firstDot)+"."+str.substr(1,str.length-1);
document.write(str);
Shai.
Here is another approach:
function process(input) {
var n = 0;
return input.replace(/\./g, function() { return n++ > 0 ? '' : '.'; });
}
But one could say that this is based on side effects and therefore not really elegant.
This isn't necessarily more elegant, but it's another way to skin the cat:
var process = function (input) {
var output = input;
if (typeof input === 'string' && input !== '') {
input = input.split('.');
if (input.length > 1) {
output = [input.shift(), input.join('')].join('.');
}
}
return output;
};
Not sure what is supposed to happen if "." is the first character, I'd check for -1 in indexOf, also if you use substr once might as well use it twice.
if ( index != -1 ) {
input = input.substr( 0, index + 1 ) + input.substr(index + 1).replace( /\./g, '' );
}
var i = s.indexOf(".");
var result = s.substr(0, i+1) + s.substr(i+1).replace(/\./g, "");
Somewhat tricky. Works using the fact that indexOf returns -1 if the item is not found.
Trying to keep this as short and readable as possible, you can do the following:
JavaScript
var match = string.match(/^[^.]*\.|[^.]+/g);
string = match ? match.join('') : string;
Requires a second line of code, because if match() returns null, we'll get an exception trying to call join() on null. (Improvements welcome.)
Objective-J / Cappuccino (superset of JavaScript)
string = [string.match(/^[^.]*\.|[^.]+/g) componentsJoinedByString:''] || string;
Can do it in a single line, because its selectors (such as componentsJoinedByString:) simply return null when sent to a null value, rather than throwing an exception.
As for the regular expression, I'm matching all substrings consisting of either (a) the start of the string + any potential number of non-dot characters + a dot, or (b) any existing number of non-dot characters. When we join all matches back together, we have essentially removed any dot except the first.
var input = '14.1.2';
reversed = input.split("").reverse().join("");
reversed = reversed.replace(\.(?=.*\.), '' );
input = reversed.split("").reverse().join("");
Based on #Tadek's answer above. This function takes other locales into consideration.
For example, some locales will use a comma for the decimal separator and a period for the thousand separator (e.g. -451.161,432e-12).
First we convert anything other than 1) numbers; 2) negative sign; 3) exponent sign into a period ("-451.161.432e-12").
Next we split by period (["-451", "161", "432e-12"]) and pop out the right-most value ("432e-12"), then join with the rest ("-451161.432e-12")
(Note that I'm tossing out the thousand separators, but those could easily be added in the join step (.join(','))
var ensureDecimalSeparatorIsPeriod = function (value) {
var numericString = value.toString();
var splitByDecimal = numericString.replace(/[^\d.e-]/g, '.').split('.');
if (splitByDecimal.length < 2) {
return numericString;
}
var rightOfDecimalPlace = splitByDecimal.pop();
return splitByDecimal.join('') + '.' + rightOfDecimalPlace;
};
let str = "12.1223....1322311..";
let finStr = str.replace(/(\d*.)(.*)/, '$1') + str.replace(/(\d*.)(.*)/, '$2').replace(/\./g,'');
console.log(finStr)
const [integer, ...decimals] = '233.423.3.32.23.244.14...23'.split('.');
const result = [integer, decimals.join('')].join('.')
Same solution offered but using the spread operator.
It's a matter of opinion but I think it improves readability.
I have strings like Name:, Call:, Phone:....and so on in my table. I am learning jQuery and was able to access the text. My tutorial has used trim() to remove any whitespaces. But I want o remove ":" from the end of each string (and yes, it always lies in the end after calling trim() method). So how to achieve it.
Its my code:
<script type="text/javascript">
$(function ()
{
$(':input[type=text], textarea').each
(
function ()
{
var newText = 'Please enter your ' +
$(this).parent().prev().text().toLowerCase().trim();
$(this).attr('value', newText);
}).one('focus', function ()
{
this.value = '', this.className = ''
}).addClass('Watermark').css('width', '300px');
});
</script>
trim(":") did not help...
You can replace all : characters:
var str = '::a:sd:';
str = str.replace(/:/g,''); // str = 'asd';
Or use a handy rtrim() function:
String.prototype.rtrim = function(character) {
var re = new RegExp(character + '*$', 'g');
return this.replace(re, '');
};
var str = '::a:sd:';
str = str.rtrim(':'); // str = '::a:sd';
In this case just use the plain old JavaScript replace or substr methods.
You can also use a regular expression that looks for colon as the last character (the character preceding the regexp end-of-string anchor "$").
"hi:".replace(/:$/, "")
hi
"hi".replace(/:$/, "")
hi
"h:i".replace(/:$/, "")
h:i
This is a simplified, inline version of the rtrim function in Blender's answer.
EDIT: Here is a test fiddle for Blender's corrected rtrim function. Note that his RegExp will delete multiple occurrences of the specified character if the string ends with multiple instances of it consecutively (example bolded below).
http://jsfiddle.net/fGrPb/5/
input = '::a:sd:' output = '::a:sd'; input = 'hi:' output = 'hi'; input = 'hi:::' output = 'hi'; input = 'hi' output = 'hi'; input = 'h:i' output = 'h:i'
To chop the last character of a string use string.slice(0,-1)
You can use a regular expression to remove the colon (:).
Replace one instance:
var with_colon = 'Stuff:';
var regex = /([^:]*):/;
var without_colon = regex.exec(with_colon)[1];
alert(without_colon);
Result: Stuff
Replace all instances:
var with_colon = 'Stuff: Things:';
var without_colon = with_colon.replace(/([^:]*):/g,'$1');
alert(without_colon);
Result: Stuff Things
var myStr = "something:";
myStr = myStr.slice(0, -1);
var a="name:";
var b=a.split(":");
alert(b[0]);
one way is to use lastIndexOf
var str='Name:, Call:, Phone:';
var index=str.lastIndexOf(":");
alert(index);
var s=str.substring(0,index);
alert(s);
DEMO
This checks if the last character is a colon. If it is, the last character is removed.
if (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
If there can be multiple trailing colons, you can replace if with while, like this:
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
You could even make a generic trim function that accepts a string and a character and trims trailing instances of that character:
var trim = function(str, chr) {
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
return str;
}
function trim(str) {
str = str.replace(/^:*/,"");
return str.replace(/:*$/,"");
}
str = str.substring(0,str.lastIndexOf(":"));
Note that this removes everything from the last : to the end of the string (for example, any whitespace after the :).