find a sentence with a specific length from inserted text using javascript - javascript

I'm working on a game in which I need to use a sentance with a specific length.
Is it possible to find and show, in any form (It could be console log or alert), every sentence(beginning with ". " and ending with ".")
with a specific length, from an inserted text by using javascript?
I thought that I would simply insert some ebook that I have and find every sentence that has 32 characters including spaces,
if anyone has an idea how to achieve that would be great :)

Take the stringified text, use the '.split' method on the string with the argument '.'
You will now have an array of all 'sentences.'
Now from there we can .filter() the sentences array to only include sentences that are of length 32:
let text = 'My name is aaron. I like stuff.'
text = text.split('.')
let sentancesOf32Length = text.filter(text => text.length === 32)

Related

How do you delete every line inside of a string that doesn't contain a specific word?

There's a string with multiple lines of random characters, I'd like to delete every line that doesn't contain the word
:tesTWORD:
For example, this part of the original string
"111"1"13648""
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
"101"1"00000368""
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
PA0545:tesTWOR:b598944d1ba4c787e411800b8043559c""
""
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b
PA0545:tesWOR:b598944d1ba4c787e411800b8043559c""
3646475
Would turn into this:
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b
So basically all lines that don't contain the exact word :tesTWORD: get deleted.
I have tried a bunch of different things like playing around with arrays, but nothing worked like it's supposed to
You can use \n to split it into an array,then filter the array,finally using join() to form a new string
str.split('\n').filter(d => d.indexOf(':tesTWORD:') > -1).join('\n')
let str = `"111"1"13648""
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
"101"1"00000368""
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
PA0545:tesTWOR:b598944d1ba4c787e411800b8043559c""
""
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b
PA0545:tesWOR:b598944d1ba4c787e411800b8043559c""
3646475`
let result = str.split('\n').filter(d => d.indexOf(':tesTWORD:') > -1).join('\n')
console.log(result)

Javascript : Create a variable that returns me only the first word of page title

I have a website page with a three words title.
how can I create a variable in Javascript that outputs only the first word of that title ?
thanks for your help !
There are a lot of way to do that. If you have these words separated by space, the simplest and straightforward you can write the following:
const firstWord = pageTitle.split(' ')[0];
If you need to extract page title from browser API, just address document.title and use it as pageTitle variable.
const firstWord = document.getElementsByTagName('title')[0].innerText.split(' ')[0]
Description:
docuemnt.getElementsByTagName('tagName') finds all the elements with the given tagName. We want only only the first element of it. Hence add put [0] next to it.
innerText gives the content of the given element.
split(" ") splits the given string into an array based on the argument. Here since we want to split into words, we use empty space ' '. Since we need only the first word, you have to again use [0]
If you need the first "word" of the title, you can:
Access the document.title
Trim any unnecessary white-space
Shift the resulting array to grab the first sequence of non-white-space characters
Note: You do not need to use the global flag for the expression, because we only care about the left-hand side of the split.
const firstWordOfTitle = document.title.trim().split(/\s+/).shift();
console.log(`First word of document: "${firstWordOfTitle}"`); // "Test"
<title>Test Title</title>

regex - Match a portion of text given begin and end of the portion in Javascript

I need to trim a very long string that can change during time. Since it's html I can use tags and attributes name to cut it regardless of the content. unfortunately I can't find a way to write the regex match. Given the following example:
This is (random characters) an example (random characters)
How can I match the (random characters) and "This is" using the rest, which is always the same? I've tried something along the lines of the followings:
^(This is)((.|\s)*an)$
This is^(?!.*(an))
but everything seems to fail. I think that the "any character or space in beetween" part makes the search go right to the end of the string and I miss the "an" part, but I can't figure it out how to add an exception to that.
I don't know javascript, but I will assume the following functions I will write in some loosely C-like code exist in some form:
string input = "This is (random characters) an example (random characters)";
string pattern = "(^This is .*) an example (.*$)";
RegexMatch match = Regex.Match( str, pattern );
string group0 = match.GetGroup(0);//this should contain the whole input
string group1 = match.GetGroup(1);//this should get the first part: This is (random characters)
string group2 = match.GetGroup(2);//this should get the second part: (random characters) at the end of the input string
Note: Normally in Regular Expressions, The parentheses create capture groups.
'Look behind' would be good for this, but unfortunately, JS doesn't support it. However, you can use a RegExp and capturing groups to get the result you want.
let matchedGroups = new RegExp(/^This is (.+) an example (.+).$/,'g')
matchGroups.exec('This is (random characters) an example (random characters).')
This returns an array:
0:"This is (random characters) an example (random characters)."
1:"(random characters)"
2:"(random characters)"
As you can see this is a little clunky, but will get you two strings that you can use.

Saving words from text into an array

I am trying to do an interesting task and currently have no idea how to do it.
I have a wiki page (ex: https://en.wikipedia.org/wiki/Moldova ) and I want to save each word from this page into an array. Further I will need to parse this array to extract some specific words.
Can someone give me a hint how can I save words from a text into an array.
And how can I solve this problem:
-For each word remove punctuation such as ,.()"' etc.
-If the words is an html tag , don't store it.
Thank you.
By using the split() method, it is used to split a string into an array of substrings, and returns the new array. Read more about it here.
var text="your text";
var punctRE = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?#\[\]^_`{|}~]/g;
text.replace(punctRE, ''); // Strip all punctuation from the string.
var myArray=text.split(" "); // Pass an empty space as a separator.

Javascript to find and replace text

I'm making an extension for google chrome and i would like to be able find certain pieces of text and replace them with random letters or numbers using javascript except the certain text is a variable entered by the user for example they enter the word dog and all words that say dog are found and replaced as explained before . HELP greatly wanted
Try using the .replace() method of JavaScript.
Supposing you have a div like so for containing text: <div id="test">Original Text</div>, use this JavaScript code:
var orignalstring = document.getElementById("test").innerHTML;
var newstring = orignalstring.replace("original","replaced");
document.getElementById("test").innerHTML = newstring;
Basically, this will identify the entire content of the whole div, then find certain text and replace those terms, like you asked. If you want to replace multiple strings in one command, try this: How to replace multiple strings with the .replace() Method?. This is a question I asked a few weeks back about .replace().
Also, try this JSFiddle: http://jsfiddle.net/tGMaN/
If you want the user to be able to define the text to replace and the replacement text, you can easily do this through text fields or a prompt box, and these values can be stored as variables which are called in the .replace() method.
The String object has lots of useful methods.
var theNewString = theString.replace(findThis, replaceWithThis);
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
// Generates a string of random letters
function generateRandomKey(number) {
var key = String();
var values = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for(var i = 0; i < number; i++) {
key += values.charAt(Math.floor(Math.random() * values.length));
}
return key;
}

Categories