This question already has answers here:
detect differences between two strings with Javascript
(2 answers)
Closed 8 years ago.
I am wondering if there is a way in JavaScript by which I can detect which part of my Strings makes them different from each other.
Let's say I have three strings as follows:
String1 = "Java1String"
String2 = "Java2String"
String3 = "Java3String"
If I choose my first String as a main one, the part which makes it different from the others is 1.
Is there any way using either JavaScript or jQuery by which I can find this part?
var String1 = "Java1String",
String2 = "Java2String",
String3 = "Java3String";
var j = 0;
for(var i = 0; i < String1.length; i++){
if(String1.charAt(i) != String2.charAt(j))
alert(String1.charAt(i) +" != "+ String2.charAt(j));
j++;
}
You can check out a demo of this code with this jsfiddle.
You can compare two strings like this. This will give you the characters which are different.
var String1 = "Java1String",
String2 = "Java2String",
String3 = "Java3String";
var j = 0;
for(var i = 0; i < String1.length; i++){
if(String1.charAt(i) != String2.charAt(j))
alert(String1.charAt(i) +" != "+ String2.charAt(j));
j++;
}
You can check out Demo of this code on this link
http://jsfiddle.net/enL9b3jv/1/
The naive solution would be to convert each string into an array and iterate over the arrays, compare the character at each index until you find an index that doesn't match, and then write that index to a variable. Below is a Jsbin that does just that, but just as DevIshOne states, there are many questions to answer here...
http://jsbin.com/dugovemoxupu/1/edit
Related
This question already has answers here:
How does adding String with Integer work in JavaScript? [duplicate]
(5 answers)
Closed 4 years ago.
I would like to combine two or more variables into the same array index but not do anything to the values, just place them together in the same array index
So
var myArray[];
var one= 1;
var two = 2;
etc...
myArray.push("one" + "two")
document.write(myArray[0];
Should output 12 or 1 2 but not add them together to show 3.
Remove double quotes and for converting to string just add a '' between them. This kind of converting is more efficience than String()
var myArray = [];
var one = 1;
var two = 2;
myArray.push(one + '' + two)
document.write(myArray[0]);
You can do this, using String to convert the numbers into strings and then + will perform string concatenation instead of numeric addition.
const myArray = [];
const one = 1;
const two = 2;
myArray.push(String(one) + String(two));
console.log(myArray);
This question already has answers here:
Remove a character at a certain position in a string - javascript [duplicate]
(8 answers)
Closed 5 years ago.
I am having problem finding the proper method to accomplish this in JS. I want to iterate through each character of string (assume all lower cased) while removing ith character only.
So if I have string abc, I will iterate it three times and it will print:
'bc' //0th element is removed
'ac' //1st element is removed
'ab' //2nd element is removed
I thought I could do it with replace, but it did not work on string having multiple same characters.
Something like this:
str = 'batman';
for(var i = 0; i < str.length; i++){
var minusOneStr = str.replace(str[i], '');
console.log(minusOneStr);
}
"atman"
"btman"
"baman"
"batan"
"btman" //need it to be batmn
"batma"
I realized this didn't work because str.replace(str[i], ''); when str[i] is a, it will replace the first instance of a. It will never replace the second a in batman. I checked on substring, splice, slice method, but none suits mf purpose.
How can I accomplish this?
Instead of using .replace() you'd just concatenate slices of the string before and after the current index.
var str = 'batman';
for (var i = 0; i < str.length; i++) {
var minusOneStr = str.slice(0, i) + str.slice(i + 1);
console.log(minusOneStr);
}
This is because, as you noted, .replace(), when given a string, always replace the first instance found.
This question already has answers here:
How to capitalize first letter of each word, like a 2-word city? [duplicate]
(4 answers)
Closed 5 years ago.
i have a task for my homework where i have to write a function that will capitalize each word in a sentence that is written into that function. The idea i had was to convert each word into an array, make a loop targeting first letter of each item of that array, and then turning that array back into a string. The code i came up with is this
function titleCase(string) {
var words = string.split(' ');
for (var i = 0; i < words.length; i++) {
const lettersUp = ((words[i])[0]).toUpperCase();
const result = words[i].replace((words[i])[0], lettersUp);
return result;
}
}
The problem i have now is that it returns only the first word of an array. From troubleshooting i have been doing i have a feeling i messed up the loop but i just have no idea how. Any help would be greatly appreciated.
Thanks.
You are returning from the first iteration, so your code won't work.
What you are looking for is something like this:
function titleCase(string) {
var words = string.split(" ");
for (var i = 0; i < words.length; i++) {
const lettersUp = ((words[i])[0]).toUpperCase();
words[i] = words[i].replace((words[i])[0], lettersUp);
}
return words.join(" ");
}
Regexes are the way to go, though. Please try and use though.
Keep it as simple as possible - there's no need for additional variables such as lettersUp, you can simply manipulate the strings in the words array.
function titleCase(str) {
var words = str.split(' ');
for (var i = 0; i < words.length; i++) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].substring(1);
}
return words.join(' ');
}
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 5 years ago.
I want regular expression which return true if any continuous three charters match.
For e.g /[money]{3,}/g
It return true for mon, one, ney and return false for mny.
Regular expressions function as a search for a character string, your application would require taking a base string and dynamically building an insane regex with many ORs and lookaheads/behinds. For your application, write a function that uses indexOf
function stringContainsSubstr(sourceStr, subStr) {
return sourceStr.indexOf(subStr) !== -1;
}
var exampleStrs = ["mon", "one", "ney", "mny"];
var str = "money";
for (var i = 0; i < exampleStrs.length; i++) {
console.log(stringContainsSubstr(str, exampleStrs[i]));
}
http://plnkr.co/edit/2mtV1NeD1MYta5v49oWr
I would not use regex, why not use indexOf, it's less code and better to read.
something like "money".indexOf("mon")>-1
Here a Demo, with all listed examples:
let values = ["mon","one", "ney", "mny"];
let shouldMatch = "money";
for (let idx = 0; idx<values.length;idx++){
console.info(values[idx], "=", shouldMatch.indexOf(values[idx])>-1);
}
But If you want to use RegExp, you could use it like this:
(BTW: this is only a "fancy" way to write the example above)
let values = ["mon","one", "ney", "mny"];
function matcher(word, value){
return (new RegExp(value)).test(word);
}
for (let idx = 0; idx<values.length;idx++){
console.info(values[idx], "=", matcher("money", values[idx]));
}
The Code Basically:
Creates a new Regular Expression exp. (new RegExp("mon")) (equal to /mon/) and than just testing, if the "pattern" matches the word "money" (new RegExp("mon")).test("money") this returns true.
Here it is all turned around, we are checking if money fits into the (sub)-pattern mon.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I have this code:
var str = 'country/city/area'
var idx = str.lastIndexOf('country/city')
// idx = 0
And idx is always 0. Shouldn't idx be 12? My goal is to use it substr() in order to take the string 'area' out of the str.
var str = 'country/city/area'
var pattern = 'country/city/'
var idx = str.lastIndexOf(pattern) + pattern.length
var substring = str.substring(idx, str.length)
Explanation
1) Define the pattern you are searching for
2) Find the beginning of the pattern and add the length of the pattern => now you are at the end
3) Copy the part behind the pattern to the end of the string
if you want to get the last word, you can search for the last forward slash and get everything after it:
str.substr(str.lastIndexOf('/') + 1)
if you want to get everything after 'country/city/' but for example you don't know if this the first part of the string, you can use
str.substr(str.indexOf('country/city/') + 13);
it's not 100% clear from your question, what exactly you are trying to achieve though.
You're going to want to add the length of the string that you search for:
var str = 'country/city/area';
var checkStr = 'country/city';
var idx = str.lastIndexOf(checkStr);
var lastCharIndex = idx + checkStr.length;
// idx = 0
// idx = 12
note - it would be 12, not 13, because you didn't include the final "/" in your lastIndexOf parameter.
May be you can achieve your goal as follows;
var str = 'country/city/area',
newStr = str.replace("/area","");
console.log(newStr);