I have a function that needs to append a sequence of numbers (starting with 1) at the end of each word in the string. Here is my function:
function insertNum(str) {
var word = new Array();
word = str.split(" ");
return src[0] + "1 " + src[1] + "2 " + src[2] + "3 " + src[3];
}
insertNum("word word word word."); // return "word1 word2 word3 word4."
insertNum("word word word."); // return "word1 word2 word3."
This should do it...
function insertNum(str) {
var index = 1;
return str.replace(/\w\b/g, function(match) {
return match + index++;
});
}
jsFiddle.
An easy way:
function insertNum(str) {
var word = new Array();
word = str.split(" ");
var tmp = "";
for (i = 1; i <= word.length; i ++) {
tmp += word[i-1] + i + " ";
}
return tmp;
}
int count = 1;
String s = "This is nice";
String a[] = s.split(" ");
for(String m : a){
System.out.print(m + count++ + " ");
}
Related
Hei, I have this function:
function frame(string) {
var words = string.split(" ");
var longestWord = 0;
var y = "*";
//Find the longest word from the string
for (var i = 0; i < words.length; i++) {
if (words[i].length > longestWord) {
longestWord = words[i].length;
}
}
console.log(y.repeat(longestWord + 4));
for (var i = 0; i < words.length; i++) {
console.log(y + " " + words[i] + " " + y);
//words[i].length = longestWord;
}
console.log(y.repeat(longestWord + 4));
}
I want that all the string has the same length as the longest string. The rest is working good. The code that is commented out is the one i tried last but is not working.
Apparently, the logic is not totally correct, but what I am missing?
Thank you
Strings are immutable in JS, you can't just overwrite the length attribute ;)
Do you mean, that you need padding after the word up to the length of the longest word? If I understood it correctly, then try something like this:
console.log(y + " " + words[i].padEnd(longestWord, " ") + " " + y);
This looks like the easiest way, but consult Can I use, if all your browsers are covered.
I would be tempted to get rid of some of the for loops to help readability. You can use Math.max and map to find the longest word and padEnd to fix the length:
function frame(string, y = '*') {
var words = string.split(" ");
let longestlength = Math.max(...words.map(w => w.length))
let header = y.repeat(longestlength + 4)
return [
header,
...words.map(word => `${y} ${word.padEnd(longestlength, ' ')} ${y}`),
header
]
}
console.log(frame("hello the word javascript is long").join('\n'))
Calculate the space left to fill and repeat it as below.
function frame(string) {
var words = string.split(" ");
var longestWord = 0;
var y = "*";
//Find the longest word from the string
for (var i = 0; i < words.length; i++) {
if (words[i].length > longestWord) {
longestWord = words[i].length;
}
}
console.log(y.repeat(longestWord + 4));
for (var i = 0; i < words.length; i++) {
spaceLeft = longestWord - words[i].length;
console.log(y + " " + words[i] + " ".repeat(spaceLeft) + " " + y);
//words[i].length = longestWord;
}
console.log(y.repeat(longestWord + 4));
}
frame('skfj dslfska sadflkdsflkdsnf ldsknflskdnaf dslkf')
The first loop for finding the max length of word seems right in second loop you can use if statement
All you have to do is that
First define an array
let a=[]
In second loop in the commented part write
if(word[I].length == longestlength){a.push(word[I])}
After that you get array containing word whose length is equal to max length
Hope it helps
function frame(string) {
var words = string.split(" ");
var longestWord = 0;
var y = "*";
//Find the longest word from the string
for (var i = 0; i < words.length; i++) {
if (words[i].length > longestWord) {
longestWord = words[i].length;
}
}
console.log(y.repeat(longestWord));
for (var i = 0; i < words.length; i++) {
console.log(words[i] + y.repeat(longestWord - words[i].length));
//words[i].length = longestWord;
}
}
frame('Lorem ipsum dolor sit amet, consectetur adipiscing elit')
maybe something like this, now every word has same length as the longest one, empty space is filled with *
See comments inline:
function frame(string) {
var words = string.split(" ");
var longestWord = "";
var y = "*";
//Find the longest word from the string
for (var i = 0; i < words.length; i++) {
if (words[i].length > longestWord.length) {
longestWord = words[i];
}
}
console.log("Longest word is: " + longestWord)
console.log(y.repeat(longestWord.length + 4));
for (var i = 0; i < words.length; i++) {
// Get the difference between the word and the longest word
var diff = longestWord.length - words[i].length;
// Pad the words with the right amount of spaces to make up the difference
console.log(y + " " + words[i] + " ".repeat(diff) + y);
}
console.log(y.repeat(longestWord.length + 4));
}
frame("The quick brown fox jumped over the lazy dog.");
I want to truncate a string with a limit of characters and a condition for the last character that should be a space (this way I have no truncated words)
Example :
var sentence = "The string that I want to truncate!";
sentence.methodToTruncate(14); // 14 is the limit of max characters
console.log("Truncated result : " + sentence); // Truncated result : The string
You can use truncate one-liner below:
const sentence = "The string that I want to truncate!";
const truncate = (str, len) => str.substring(0, (str + ' ').lastIndexOf(' ', len));
console.log(truncate(sentence, 14));
Here's how you can truncate by words and given limit -
String.prototype.methodToTruncate = function(n) {
var parts = this.split(" ");
var result = "";
var i = 0;
while(result.length >= n || i < parts.length) {
if (result.length + parts[i].length > n) {
break;
}
result += " " + parts[i];
i++;
}
return result;
}
var sentence = "The string that I want to truncate!";
console.log("Truncated result : " + sentence.methodToTruncate(14)); // Truncated result : The string
First you can have a max substring of your string, and then recursively remove the letters until you find spaces.
Note that this response is made without doing monkey patching and so, not extending String.prototype :
var sentence = "Hello a";
var a = methodToTruncate(sentence, 5); // 14 is the limit of max characters
console.log("Truncated result : " + a); // Truncated result : The string
function methodToTruncate(str, num) {
if(num>= str.length){ return str;}
var res = str.substring(0, num);
while (str[res.length] != " " && res.length != 0) {
console.log(res.length)
res = res.substring(0, res.length-1);
}
return res;
}
I am creating a list of words from a String. I then split that string into individual words, gather a count of how many times each word is repeated, and display it. Everything there works perfectly. However, the result displays the words and counts in no specific order. I will want to display them with the highest number first. I have generated the following code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="analyze()">Analyze</button>
<p id="displayText"></p>
<script>
function analyze() {
var str = "This this is is is is is is is is is is is is is is is just just a test test test";
var res = str.split(" ");
document.getElementById("displayText").innerHTML = res;
document.getElementById("displayText").innerHTML += "<br/><br/>The amount of words is: " + res.length + "<br/><br/><br/>";
document.getElementById("displayText").innerHTML += "The list of words:<br/><br/>";
var words = [];
var wordsWithCount = [];
for (i = 0; i < res.length; i++) {
words.push(res[i]);
document.getElementById("displayText").innerHTML += words[i] + "<br/><br/>";
}
var current = null;
var cnt = 0;
for (var i = 0; i < words.length; i++) {
if (words[i] != current) {
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
current = words[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
wordsWithCount.sort();
document.getElementById("displayText").innerHTML += "<br/><br/><br/><br/><br/>The list of SORTED words:<br/><br/>";
for (i = 0; i < wordsWithCount.length; i++) {
document.getElementById("displayText").innerHTML += wordsWithCount[i] + "<br/><br/>";
}
}
</script>
</body>
</html>
This is the last bit of the output. As you can see, it's being sorted, but only by first digit. Thus, 15 is displayed before 2. Any thoughts?
The list of SORTED words:
1 - This
1 - a
1 - this
15 - is
2 - just
3 - test
I will most likely need to break this into two arrays at some point, because I will want the user to be able to copy and paste all of the words, without the numbers. However, I assume that will need to be the last step, because if I break the frequency of each word into it's own array of numbers, and keep the words in their own array, then the sort function will sort one array, and the other array will not follow.
Using a parseInt() method and the solution found here (How to sort an array of integers correctly) to the mix it works!
replace wordsWithCount.sort(); with:
function sortNumber(a,b) {
return parseInt(a) - parseInt(b);
}
wordsWithCount.sort(sortNumber);
Live here: https://www.w3schools.com/code/tryit.asp?filename=FFGXRIN0VZWO
Do it using Intl.Collator. Like this:
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var test = ['1 - this', '3 - this', '14 - this'];
test.sort(collator.compare);
Outputs ["1 - this", "3 - this", "14 - this"]
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var test = ['1 - this', '3 - this', '14 - this'];
console.log(test.sort(collator.compare));
You can just add a custom compare function to pass into your wordsWithCount.sort() call. Here I declared a function called compareWordCount and used the sugfested method by #Pointy; using parseInt to ignore all non integer parts appended to array value. Take a look at this working snippet:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="analyze()">Analyze</button>
<p id="displayText"></p>
<script>
function compareWordCount(a,b) {
if (parseInt(a) < parseInt(b))
return -1;
return 1;
}
function analyze() {
var str = "This this is is is is is is is is is is is is is is is just just a test test test";
var res = str.split(" ");
document.getElementById("displayText").innerHTML = res;
document.getElementById("displayText").innerHTML += "<br/><br/>The amount of words is: " + res.length + "<br/><br/><br/>";
document.getElementById("displayText").innerHTML += "The list of words:<br/><br/>";
var words = [];
var wordsWithCount = [];
for (i = 0; i < res.length; i++) {
words.push(res[i]);
document.getElementById("displayText").innerHTML += words[i] + "<br/><br/>";
}
var current = null;
var cnt = 0;
for (var i = 0; i < words.length; i++) {
if (words[i] != current) {
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
current = words[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
wordsWithCount.sort(compareWordCount);
document.getElementById("displayText").innerHTML += "<br/><br/><br/><br/><br/>The list of SORTED words:<br/><br/>";
for (i = 0; i < wordsWithCount.length; i++) {
document.getElementById("displayText").innerHTML += wordsWithCount[i] + "<br/><br/>";
}
}
</script>
</body>
</html>
Want to know if the substring of string is in the another string.
For eg..
var firstString= test123;
var secondString= nest145;
var thirdString= test456;
var fourString= teating456;
Result should be after comparing firstString and secondString
est1 is matched.
Result should be after comparing firstString and thirdString
test is matched.
Result should be after comparing firstString and fourString
No match found.
Limit to check the word-length can be decided.For the above example it is 4
Here is a simple sample, where the matched letters needs to be next after each other.
var firstString = 'test123';
var secondString = 'nest145';
var thirdString = 'test456';
var fourString = 'teating456';
function findMatchedChars(str1, str2, limit) {
var result = '', s1 = str1, s2 = str2;
if (str2.length > str1.length) {
s1 = str2;
s2 = str1;
}
for (var x = 0; x < s1.length; x++) {
if (s1[x] == s2[x]) {
result += s1[x];
} else {
if (result.length > 0 && result.length >= limit) return result;
result = '';
}
}
if (result.length > 0 && result.length >= limit) return result;
return 'No matches';
}
alert(findMatchedChars(firstString,secondString,4));
alert(findMatchedChars(firstString,thirdString,4));
alert(findMatchedChars(firstString,fourString,4));
This is LCS problem with tow string...
LCS
Here is the regex version:
var firstString = 'test123';
var secondString = 'nest145';
var thirdString = 'test456';
var fourString = 'teating456';
function findDups(str1, str2, limit) {
var re = '.*([^\\s]{' + limit + '}).*\\s+.*\\1.*'
var m = (str1 + " " + str2).match(re)
if (m != null) {
alert(m[1])
} else
alert('No matches')
}
findDups(firstString, secondString, 4)
findDups(firstString, thirdString, 4)
findDups(firstString, fourString, 4)
How can I delete a part of a string by using only the index (no regex in case the character at index exists elsewhere)?
I use this, but it seems extremely convulted!!
var str = "stringIwant to delete from";
var stringCodeLastIndex = str.length - 1;
var index2delete = 1;
var stringStart, stringEnd, finalString;
if (index2delete == 0) {
stringStart = "";
} else {
stringStart = str.substr(0, index2delete);
}
if (index2delete < stringCodeLastIndex) {
stringEnd = str.substr(index2delete + 1);
} else {
stringEnd = "";
}
finalString = stringStart + stringEnd;
substring is smart enough to handle invalid indexes on its own:
str = "someXXXstring";
del = 4;
len = 3
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
str = "somestringXXX";
del = 10;
len = 20
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
str = "somestring";
del = 0;
len = 200
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
In your case, it's easier to use slice():
finalString = str.slice(0,index2delete)+str.slice(index2delete+1)
If you want to remove more characters, you can have 2 indexes:
finalString = str.slice(0,start_index)+str.slice(endindex+1)
http://www.w3schools.com/jsref/jsref_slice_string.asp
To remove one specific index from your string:
str.substr(0, indexToDelete) + str.substr(indexToDelete+1, str.length);
to remove a range of indexes from your string:
str.substr(0, startIndexToDelete) + str.substr(endIndexToDelete+1, str.length);
var str = "stringIwant to delete from";
var index2delete = 1;
arStr = str.split(""); // Making a JS Array of each characters
arStr.splice(index2delete,1); // Using array method to remove one entry at specified index
var finalString = arStr.join(''); // Convert Array to String
Result :
sringIwant to delete from
fiddle
then create a substring and use replace('your substring', '') it will replace the part of your string with a empty space