remove characters in string after specific occurrence - javascript

Hoping you guys can help me out.
I have a dynamic url and I need some javascript to basically trim the string after the specific occurrence of a character.
EXAMPLE:
I have this url
Assessment/testdir2/TestDIR3/lecture slides 1as.pdf
and I need to remove everything after the 2nd slash and including the 2nd slash.
How would I do this?

A very basic JS solution:
function removeAfterSlash(word, numberOfElements) {
var splitWord = word.split('/');
var newWord = '';
for(var i = 0; i < numberOfElements; i++) {
if(i != (numberOfElements - 1)) {
newWord += splitWord[i] + '/';
} else {
newWord += splitWord[i];
}
}
document.write(newWord);
}
removeAfterSlash('Assessment/testdir2/TestDIR3/lecture slides 1as.pdf', 1);
Simply split's the word into an array by looking for a / and then you can join the elements you need back together. The function takes the word and how many 'segments' you want to join back together.
See it on jsfiddle.

Try this:
var url= "Assessment/testdir2/TestDIR3/lecture slides 1as.pdf"
var locs = myString.split('/');
var newUrl = "";
for (var i = 2; i < locs.length; i ++) {
newUrl += "/" + locs[i];
}
This method will then ignore the first two folders and will work regardless of how many other folders you have in the url.

Related

Removing duplicate spaces from input

<textarea id="check" cols="50" rows="20"></textarea>
<script>
var text = document.getElementById("check").value;
var lengthA = text;
for (var i = 0; i < lengthA.length; i++) {
var space = " ";
if (lengthA[i] === space) {
var next = lengthA[i] + 1;
if (next === space) {
lengthA.replace(lengthA[i], "");
}
}
}
var length3 = lengthA.length - length2;
var words = length3 + 1;
</script>
Alright bois, me got a problemo! Im attempting to make a word counter through the law that each space equals a word (1:1). Im not sure why it is not working, it makes sense to me in my mind. I have attempted several alternatives and dwelled hours upon trying to fix this chunk. Thank you in advance to anyone that answers, even if it doesn't work! :)
EDIT: Regular expressions did the trick and replaced the incorrectly used for loop and if statements. Thanks
How about just the below -
var text = document.getElementById("check").value.replace (/ +/g, " ");
Not sure, why you would need a for loop to begin with.
/ +/ will more than 1 space
g will do all the changes throughout the text
To remove the duplicate space, the following code
lengthA.replace(lengthA[i], "");
should be
lengthA = lengthA.substring(0, i) + lengthA.substring(i + 1);
// i should not increase
i--;
continue;
You misunderstand the usage of replace.
Use str.replace() of JavaScript to do this. This will remove not only space but also work for tabs, newlines etc.
Usage:
var string = string.replace(/\s\s+/g, ' ');
So change below code:
var lengthA = text;
for (var i = 0; i < lengthA.length; i++) {
var space = " ";
if (lengthA[i] === space) {
var next = lengthA[i] + 1;
if (next === space) {
lengthA.replace(lengthA[i], "");
}
}
}
To this:
var lengthA = text.replace(/\s\s+/g, ' ');
Reference here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Logic of hangman game with javascript

I am trying to build a hangman game and I need help with the logic. I am in a beginners class so I want to try and build this using beginners syntax. What I am trying to figure out
2) My issue is I need to display dashes (-) that represent blank lines and they need to be the same length of the randomly chosen word. In addition, every time a letter is correctly guessed, I need to replace the dashes with the correctly chosen letter. A solution I have thought of is making an empty array and then assigning it the dash signs in a for loop that is the length of the string and then replacing the indexes of specific dashes with matched letters, but I am not sure if this will work.
var randomWords = ['rock', 'paper', 'scissors'];
var numWins = 0;
var chosenWord = randomWords[Math.floor(Math.random() * randomWords.length)];
document.onkeyup = function(event) {
// var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
var dashes = "";
for (var x = 0; x < chosenWord.length; x++) {
dashes += " - ";
// document.getElementById("word").innerHTML = blankLines;
// document.getElementById("word").innerHTML = ;
}
document.getElementById("word").innerHTML = dashes;
Trying to replace a dash with a letter in lines below. But both commented out code and non commented out codes work. That is why I am thinking of using an empty array but not sure if I can fill it with data using a foor loop
// for (x = 0; x < chosenWord.length; x++)
// {
// dashes[x] = "a";
// dahes.charAt(x) = 'a';
// }
dashes.charAt(0) = "a";
document.getElementById("test2").innerHTML = dashes;
This one should work. In the first case (if there's a white space in the word) it will display a whitespace. In the second case, it will replace every letter of the word with a dash.
var dashes = "";
for (i = 0; i < chosenWord.length; i++) {
if (chosenWord.charAt(i) == " ") {
dashes += " ";
} else {
dashes += "-";
}
}

Remove comma from javascript array

Hi all I am framing a url with Query string in javascript as follows every thing works fine but a comm is coming in between the query string so can some one help me
<script type="text/javascript">
function RedirectLocation() {
var cntrl = "Q1;Q2";
var str_array = cntrl.split(';');
var cnt = str_array.length;
if (cnt == 0) {
location.href = '/callBack.aspx';
}
else {
var arr = [];
for (var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
arr.push(str_array[i] + '=1');
if (i != str_array.length - 1) {
arr.push('&');
}
}
location.href = '/Sample.aspx?' + arr;
}
}
</script>
This is giving me the query string as follows Sample.aspx?Q1=1,&,Q2=1 I need this to be like `Sample.aspx?Q1=1&Q2=1
To remove the commas from a string you could simply do
s = s.replace(/,/g,'');
But in your specific case, what you want is not to add the commas. Change
location.href = '/Sample.aspx?' + arr;
to
location.href = '/Sample.aspx?' + arr.join('');
What happens is that adding an array to a string calls toString on that array and that function adds the commas :
""+["a","b"] gives "a,b"
Don't rely on the implicit string conversion (which concatenates the array elements with a comma as separator), explicitly .join the array elements with &:
var arr = [];
for (var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
arr.push(str_array[i] + '=1');
}
location.href = '/Sample.aspx?' + arr.join('&');
Think about it like this: You have a set of name=value entries which you want to have separated by &.
You can use arr.join(glue) to concatenate Array elements with something inbetween. In your case glue would be an empty string arr.join("").

Javascript: matching a dynamic string against an array

I'm attempting to teach myself javascript. I chose something I assumed was simple, but ran into problems relatively quickly.
I'm attempting to search a string for another string given by the user.
My code so far is:
var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = [];
var one = 0;
var two = 0;
var k = 0;
var sourceSearch = function(text) {
for(i = 0; i < source.length; i++) { //for each character in the source
if(source[i] === searchString[0]) { //if a character in source matches the first element in the users input
one = source.indexOf(i); //confused from here on
for(p = searchString.length; p > 0; p--) {
}
}
}
};
sourceSearch(searchString);
My idea was:
check to see if the first loop finds a character that matches the first character in the user input
if it matches, check to see if the next X characters after the first match the next X characters in the source string
if they all match, push them to the hits array
My problem: I have no idea how to iterate along the arrays without nesting quite a few if statements, and even then, that wouldn't be sufficient, considering I want the program to work with any input.
Any ideas would be helpful. Thanks very much in advance.
Note: There are a few un-used variables from ideas I was testing, but I couldn't make them work.
You can try:
if (source.indexOf(searchString) !== -1) {
// Match!
}
else
{
//No Match!
}
As the other answers so far point out, JavaScript strings have an indexOf function that does what you want. If you want to see how it's done "by hand", you can modify your function like this:
var sourceSearch = function(text) {
var i, j, ok; // always declare your local variables. globals are evil!
// for each start position
for(i = 0; i < source.length; i++) {
ok = true;
// check for a match
for (j = searchString.length - 1; ok && j >= 0; --j) {
ok = source[i + j] === searchString[j];
}
if (ok) {
// searchString found starting at index i in source
}
}
};
This function will find all positions in source at which searchString was found. (Of course, you could break out of the loop on the first success.) The logic is to use the outer loop to advance to each candidate start position in source and use the inner loop to test whether that position actually is the position of a match to searchString.
This is not the best algorithm for searching strings. The built-in algorithm is much faster (both because it is a better algorithm and because it is native code).
to follow your approach, you can just play with 2 indexes:
var sourceSearch = function(text) {
j = 0;
for(i = 0; i < source.length; i++) {
if(source[i] === text[j]) {
j++;
} else {
j = 0;
}
if (j == text.length) {
console.log(i - j); //this prints the starting index of the matching substring
}
}
};
These answers are all pretty good, but I'd probably opt for something like this:
var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = source.split(searchString);
var hitsCount = hits.length - 1;
This way you have all of the data you need to figure out where each hit occurred in he source, if that's important to you.

Javascript word-count for any given DOM element

I'm wondering if there's a way to count the words inside a div for example. Say we have a div like so:
<div id="content">
hello how are you?
</div>
Then have the JS function return an integer of 4.
Is this possible? I have done this with form elements but can't seem to do it for non-form ones.
Any ideas?
g
If you know that the DIV is only going to have text in it, you can KISS:
var count = document.getElementById('content').innerHTML.split(' ').length;
If the div can have HTML tags in it, you're going to have to traverse its children looking for text nodes:
function get_text(el) {
ret = "";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
ret += node.nodeType != 1 ? node.nodeValue : get_text(node);
}
}
return ret;
}
var words = get_text(document.getElementById('content'));
var count = words.split(' ').length;
This is the same logic that the jQuery library uses to achieve the effect of its text() function. jQuery is a pretty awesome library that in this case is not necessary. However, if you find yourself doing a lot of DOM manipulation or AJAX then you might want to check it out.
EDIT:
As noted by Gumbo in the comments, the way we are splitting the strings above would count two consecutive spaces as a word. If you expect that sort of thing (and even if you don't) it's probably best to avoid it by splitting on a regular expression instead of on a simple space character. Keeping that in mind, instead of doing the above split, you should do something like this:
var count = words.split(/\s+/).length;
The only difference being on what we're passing to the split function.
Paolo Bergantino's second solution is incorrect for empty strings or strings that begin or end with whitespaces. Here's the fix:
var count = !s ? 0 : (s.split(/^\s+$/).length === 2 ? 0 : 2 +
s.split(/\s+/).length - s.split(/^\s+/).length - s.split(/\s+$/).length);
Explanation: If the string is empty, there are zero words; If the string has only whitespaces, there are zero words; Else, count the number of whitespace groups without the ones from the beginning and the end of the string.
string_var.match(/[^\s]+/g).length
seems like it's a better method than
string_var.split(/\s+/).length
At least it won't count "word " as 2 words -- ['word'] rather than ['word', '']. And it doesn't really require any funny add-on logic.
Or just use Countable.js to do the hard job ;)
document.deepText= function(hoo){
var A= [];
if(hoo){
hoo= hoo.firstChild;
while(hoo!= null){
if(hoo.nodeType== 3){
A[A.length]= hoo.data;
}
else A= A.concat(arguments.callee(hoo));
hoo= hoo.nextSibling;
}
}
return A;
}
I'd be fairly strict about what a word is-
function countwords(hoo){
var text= document.deepText(hoo).join(' ');
return text.match(/[A-Za-z\'\-]+/g).length;
}
alert(countwords(document.body))
Or you can do this:
function CountWords (this_field, show_word_count, show_char_count) {
if (show_word_count == null) {
show_word_count = true;
}
if (show_char_count == null) {
show_char_count = false;
}
var char_count = this_field.value.length;
var fullStr = this_field.value + " ";
var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
var splitString = cleanedStr.split(" ");
var word_count = splitString.length -1;
if (fullStr.length <2) {
word_count = 0;
}
if (word_count == 1) {
wordOrWords = " word";
} else {
wordOrWords = " words";
}
if (char_count == 1) {
charOrChars = " character";
} else {
charOrChars = " characters";
}
if (show_word_count & show_char_count) {
alert ("Word Count:\n" + " " + word_count + wordOrWords + "\n" + " " + char_count + charOrChars);
} else {
if (show_word_count) {
alert ("Word Count: " + word_count + wordOrWords);
} else {
if (show_char_count) {
alert ("Character Count: " + char_count + charOrChars);
}
}
}
return word_count;
}
The get_text function in Paolo Bergantino's answer didn't work properly for me when two child nodes have no space between them. eg <h1>heading</h1><p>paragraph</p> would be returned as headingparagraph (notice lack of space between the words). So prepending a space to the nodeValue fixes this. But it introduces a space at the front of the text but I found a word count function that trims it off (plus it uses several regexps to ensure it counts words only). Word count and edited get_text functions below:
function get_text(el) {
ret = "";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
ret += node.nodeType != 1 ? ' '+node.nodeValue : get_text(node);
}
}
return ret;
}
function wordCount(fullStr) {
if (fullStr.length == 0) {
return 0;
} else {
fullStr = fullStr.replace(/\r+/g, " ");
fullStr = fullStr.replace(/\n+/g, " ");
fullStr = fullStr.replace(/[^A-Za-z0-9 ]+/gi, "");
fullStr = fullStr.replace(/^\s+/, "");
fullStr = fullStr.replace(/\s+$/, "");
fullStr = fullStr.replace(/\s+/gi, " ");
var splitString = fullStr.split(" ");
return splitString.length;
}
}
EDIT
kennebec's word counter is really good. But the one I've found includes a number as a word which is what I needed. Still, that's easy to add to kennebec's. But kennebec's text retrieval function will have the same problem.
This should account for preceding & trailing whitespaces
const wordCount = document.querySelector('#content').innerText.trim().split(/\s+/).length;
string_var.match(/[^\s]+/g).length - 1;

Categories