The replace function returns the new string with the replaces, but if there weren't any words to replace, then the original string is returned. Is there a way to know whether it actually replaced anything apart from comparing the result with the original string?
A simple option is to check for matches before you replace:
var regex = /i/g;
var newStr = str;
var replaced = str.search(regex) >= 0;
if(replaced){
newStr = newStr.replace(regex, '!');
}
If you don't want that either, you can abuse the replace callback to achieve that in a single pass:
var replaced = false;
var newStr = str.replace(/i/g, function(token){replaced = true; return '!';});
As a workaround you can implement your own callback function that will set a flag and do the replacement. The replacement argument of replace can accept functions.
Comparing the before and after strings is the easiest way to check if it did anything, there's no intrinsic support in String.replace().
[contrived example of how '==' might fail deleted because it was wrong]
Javascript replace is defected by design. Why? It has no compatibility with string replacement in callback.
For example:
"ab".replace(/(a)(b)/, "$1$2")
> "ab"
We want to verify that replace is done in single pass. I was imagine something like:
"ab".replace(/(a)(b)/, "$1$2", function replacing() { console.log('ok'); })
> "ab"
Real variant:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
return "$1$2";
})
> ok
> "$1$2"
But function replacing is designed to receive $0, $1, $2, offset, string and we have to fight with replacement "$1$2". The solution is:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
// arguments are $0, $1, ..., offset, string
return Array.from(arguments).slice(1, -2)
.reduce(function (pattern, match, index) {
// '$1' from strings like '$11 $12' shouldn't be replaced.
return pattern.replace(
new RegExp("\\$" + (index + 1) + "(?=[^\\d]|$)", "g"),
match
);
}, "$1$2");
});
> ok
> "ab"
This solution is not perfect. String replacement itself has its own WATs. For example:
"a".replace(/(a)/, "$01")
> "a"
"a".replace(/(a)/, "$001")
> "$001"
If you want to care about compatibility you have to read spec and implement all its craziness.
If your replace has a different length from the searched text, you can check the length of the string before and after. I know, this is a partial response, valid only on a subset of the problem.
OR
You can do a search. If the search is successfull you do a replace on the substring starting with the found index and then recompose the string. This could be slower because you are generating 3 strings instead of 2.
var test = "Hellllo";
var index = test.search(/ll/);
if (index >= 0) {
test = test.substr(0, index - 1) + test.substr(index).replace(/ll/g, "tt");
}
alert(test);
While this will require multiple operations, using .test() may suffice:
const regex = /foo/;
const yourString = 'foo bar';
if (regex.test(yourString)) {
console.log('yourString contains regex');
// Go ahead and do whatever else you'd like.
}
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.
With indexOf you can check wether a string contains another string.
Seems like you might want to use that.
have a look at string.match() or string.search()
After doing any RegExp method, read RegExp.lastMatch property:
/^$/.test(''); //Clear RegExp.lastMatch first, Its value will be ''
'abcd'.replace(/bc/,'12');
if(RegExp.lastMatch !== '')
console.log('has been replaced');
else
console.log('not replaced');
Related
I have a variable which contain a string and I want to return only the letters from regular expression (“b” and “D”) or any letter that I indicate on regular expression from match().
var kk = "AaBbCcDd".match(/b|D/g);
kk.forEach(function(value,index){
console.log(value,index)
});
My problem is that regular expression I think because is returning b and D but the index is not the index from kk variable and I'm not really sure, why ... so if someone can help me a little bit because I stuck
The match method from javascript only returns an array with the given match:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match
You would need to implement a new function which will loop through all characters of your string and return the given index of the matches.
This method could use the function search from String.prototype: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/search
You have to write a new function to get the index of the matched regex like a sample below:-
var re = /bar/g,
str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
alert("match found at " + match.index);
}
Hope this will help you
Actually this is the answer :
var kk = "AaBbCcDd".match(/B?d?/g);
kk.forEach(function(value,index){
console.log(value,index)
});
if someone will encounter this scenario ...
The match() regular expresion B?d? will return an array indicating the position of "B" and "d" of the initial array kk.
As a follow up to this question (not by me), I need to replace leading numbers of an id with \\3n (where n is the number we're replacing).
Some examples:
"1foo" -> "\\31foo"
"1foo1" -> "\\31foo1"
"12foo" -> "\\31\\32foo"
"12fo3o4" -> "\\31\\32fo3o4"
"foo123" -> "foo123"
Below is a solution that replaces every instance of the number, but I don't know enough regex to make it stop once it hits a non-number.
function magic (str) {
return str.replace(/([0-9])/g, "\\3$1");
}
... Or is regex a bad way to go? I guess it would be easy enough to do it, just looping over each character of the string manually.
Here is a way to achieve what you need using a reverse string + look-ahead approach:
function revStr(str) {
return str.split('').reverse().join('');
}
var s = "12fo3o4";
document.write(revStr(revStr(s).replace(/\d(?=\d*$)/g, function (m) {
return m + "3\\\\";
}))
);
The regex is matching a number that can be followed by 0 or more numbers only until the end (which is actually start) of a reversed string (with \d(?=\d*$)). The callback allows to manipulate the match (we just add reversed \\ and 3. Then, we just reverse the result.
Just use two steps: first find the prefix, then operate on its characters:
s.replace(/^\d+/, function (m) {
return [].map.call(m, function (c) {
return '\\3' + c;
}).join('');
});
No need to emulate any features.
Here is how I would have done it:
function replace(str) {
var re = /^([\d]*)/;
var match = str.match(re)[0];
var replaced = match.replace(/([\d])/g, "\\3$1");
str = str.replace(match, replaced);
return str;
}
document.write(replace("12fo3o4"));
Don't get me wrong: the other answers are fine! My focus was more on readability.
How can I convert PascalCase string into underscore_case/snake_case string? I need to convert dots into underscores as well.
eg. convert
TypeOfData.AlphaBeta
into
type_of_data_alpha_beta
You could try the below steps.
Capture all the uppercase letters and also match the preceding optional dot character.
Then convert the captured uppercase letters to lowercase and then return back to replace function with an _ as preceding character. This will be achieved by using anonymous function in the replacement part.
This would replace the starting uppercase letter to _ + lowercase_letter.
Finally removing the starting underscore will give you the desired output.
var s = 'TypeOfData.AlphaBeta';
console.log(s.replace(/(?:^|\.?)([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
OR
var s = 'TypeOfData.AlphaBeta';
alert(s.replace(/\.?([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
any way to stop it for when a whole word is in uppercase. eg. MotorRPM into motor_rpm instead of motor_r_p_m? or BatteryAAA into battery_aaa instead of battery_a_a_a?
var s = 'MotorRMP';
alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
str.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
u're welcome
var s1 = 'someTextHere';
var s2 = 'SomeTextHere';
var s3 = 'TypeOfData.AlphaBeta';
var o1 = s1.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
var o2 = s2.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
var o3 = s3.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
console.log(o1);
console.log(o2);
console.log(o3);
Alternatively using lodash:
lodash.snakeCase(str);
Example:
_.snakeCase('TypeOfData.AlphaBeta');
// ➜ 'type_of_data_alpha_beta'
Lodash is a fine library to give shortcut to many everyday js tasks.There are many other similar string manipulation functions such as camelCase, kebabCase etc.
This solution solves the non-trailing acronym issue with the solutions above
I ported the code in 1175208 from Python to JavaScript.
Javascript Code
function camelToSnakeCase(text) {
return text.replace(/(.)([A-Z][a-z]+)/, '$1_$2').replace(/([a-z0-9])([A-Z])/, '$1_$2').toLowerCase()
}
Working Examples:
camelToSnakeCase('thisISDifficult') -> this_is_difficult
camelToSnakeCase('thisISNT') -> this_isnt
camelToSnakeCase('somethingEasyLikeThis') -> something_easy_like_this
"alphaBetaGama".replace(/([A-Z])/g, "_$1").toLowerCase() // alpha_beta_gamma
Problem - Need to convert a camel-case string ( such as a property name ) into underscore style to meet interface requirements or for meta-programming.
Explanation
This line uses a feature of regular expressions where it can return a matched result ( first pair of () is $1, second is $2, etc ).
Each match in the string is converted to have an underscore ahead of it with _$1 string provided. At that point the string looks like alpha_Beta_Gamma.
To correct the capitalization, the entire string is converted toLowerCase().
Since toLowerCase is a fairly expensive operation, its best not to put it in the looping handler for each match-case, and run it once on the entire string.
After toLowerCase it the resulting string is alpha_beta_gamma ( in this example )
This will get you pretty far: https://github.com/domchristie/humps
You will probably have to use regex replace to replace the "." with an underscore.
I found this but I edited it so suit your question.
const camelToSnakeCase = str => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`).replace(/^_/,'')
Good examples for js:
Snake Case
Kebab Case
Camel Case
Pascal Case
have here
function toCamelCase(s) {
// remove all characters that should not be in a variable name
// as well underscores an numbers from the beginning of the string
s = s.replace(/([^a-zA-Z0-9_\- ])|^[_0-9]+/g, "").trim().toLowerCase();
// uppercase letters preceeded by a hyphen or a space
s = s.replace(/([ -]+)([a-zA-Z0-9])/g, function(a,b,c) {
return c.toUpperCase();
});
// uppercase letters following numbers
s = s.replace(/([0-9]+)([a-zA-Z])/g, function(a,b,c) {
return b + c.toUpperCase();
});
return s;
}
Try this function, hope it helps.
"TestString".replace(/[A-Z]/g, val => "_" + val.toLowerCase()).replace(/^_/,"")
replaces all uppercase with an underscore and lowercase, then removes the leading underscore.
A Non-Regex Answer that converts PascalCase to snake_case
Note: I understand there are tons of good answers which solve this question elegantly. I was recently working on something similar to this where I chose not to use regex. So I felt to answer a non-regex solution to this.
const toSnakeCase = (str) => {
return str.slice(0,1).toLowerCase() + str.split('').slice(1).map((char) => {
if (char == char.toUpperCase()) return '_' + char.toLowerCase();
else return char;
}).join('');
}
Eg.
inputString = "ILoveJavascript" passed onto toSnakeCase()
would become "i_love_javascript"
I'm trying to do a URL GET variable replace, however the regular expression for checking whether the variable exists in amongst other GET variables is returning true when I am expecting it to return false.
The pattern I am using is: &sort=.*&
Test URL: http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter's value?
Full code:
var sort = getOptionValue($(this).attr('id'));
var url = document.URL;
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
if(url.search('/&sort=.*&/i')) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i')) {
url.replace('/&sort=.*/i','&sort='+sort);
}
}
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter's value?
Well, you are using String.search, which, according to the linked documentation:
If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1.
So it will return -1, or 0 or greater when there is a match. So you should test for -1, not truthiness.
Also, there is no need to pass the regexes as strings, you might as well use:
url.replace(/&sort=.*&/i,'&sort='+sort+'&');
Further, keep in mind that replace will create a new string, not replace in the string (strings in Javascript are immutable).
Finally, I don't see the need for searching for the string, and then replacing it -- it seems that you always want to replace &sort=SOMETHING with &sort=SOMETHING_ELSE, so just do that:
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
url = url.replace(/&sort=[^&]*/i, '&sort=' + sort);
}
The javascript string function search() returns -1 if not found, not false. Your code should read:
if(url.search('/&sort=.*&/i') != -1) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i') != -1) {
url.replace('/&sort=.*/i','&sort='+sort);
}
You should check
if(url.search('/&sort=.*&/i') >= 0)
then it should work
You could use this code
var url = 'http://localhost/search?location=any&sort=asc';
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
console.log(vars);
//vars is an object with two properties: location and sort
This can be done by using
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + sort);
The match broken down
Group 1 matches for ? or &
Group 2 matches sort=
Group 3 matches anything that is not a & or ?
Then "$1$2" + sort will replace all 3 group matches with the first 2 + your variable
examples using string "REPLACE" instead of your sort variable
url = "http://localhost/search?location=any&sort=asc&a=z"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?location=any&sort=REPLACE&a=z"
url = "http://localhost/search?location=any&sort=asc"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?location=any&sort=REPLACE"
url = "http://localhost/search?sort=asc"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?sort=REPLACE"
url = "http://localhost/search?sort=asc&z=y"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?sort=REPLACE&z=y"
The pattern I am using is: &sort=.*& Test URL:
http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on
the basis that their is no ampersand character following the sort
parameter's value?
you are assuming right. But in your code you have else if(url.search('/&sort=.*/i')) which will match and thus still replace the value.
You should also note that your code would turn http://localhost/search?sort=asc&location=any&some=more into http://localhost/search?sort=asc&some=more. that's because because .* is greedy (trying to match as much as possible). You can avoid that by telling it to match as little as possible by appending a ? like so .*?.
That said, I believe you may be better off with a library that knows how URLs actually work. You're not compensating for parameter position, possible escaped values etc. I suggest you have a look at URI.js and replace your wicked regex with
var uri = URI(document.URL),
data = uri.query(true);
data.foo = 'bazbaz';
uri.query(data);
In most languages like C# for example given a string you can test (boolean) if that string contains another string, basically a subset of that string.
string x = test2;
if(x.contains("test"))
// do something
How can I do this in a simple way with Javascript/Jquery?
This is done with indexOf, however it returns -1 instead of False if not found.
Syntax
string.indexOf(searchValue[, fromIndex])
Parameters
searchValue -
A string representing the value to search for.
fromIndex -
The location within string to start the search from. It can be any integer between 0 and the length of string. The default value is 0.
Return
The first index in string at which the start of the substring can be found, or -1 if string does not contain any instances of the substring.
As Paolo and cletus said, you can do it using indexOf().
Valid to mention is that it is a javascript function, not a jQuery one.
If you want a jQuery function to do this you can use it:
jQuery.fn.contains = function(txt) { return jQuery(this).indexOf(txt) >= 0; }
The indexOf operator works for simple strings. If you need something more complicated, it's worth pointing out that Javascript supports regular expressions.
A simple contains can also be useful for example:
<div class="test">Handyman</div>
$(".test:contains('Handyman')").html("A Bussy man");
A working example, using just indexOf and jQuery
// Add span tag, if not set
$(document).ready(function(c) {
$('div#content ul.tabs li a').each(function(c){
// Add span wrapper if not there already
if( $(this).html().indexOf('span') == -1){
$(this).html('<span class="tab">' + $(this).html() + '</span>');
}
});
});
DT
Try to implement this
function function1() {
var m = document.all.myDiv.contains(myB);
if (m == true){
m = "YES"
} else {
m = "NO"
}
alert(m)
}