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)
I am using the below string and I want to return the substring with the blankspaces in javascript.
How can I do this?
As of now I used the normal substring function but its giving me the result after removing the blankspaces.
var Sting="CREC 20140615001CREC_GLOSS 18_0000033122 GLO4265 SGLB201406152014090120140531 TESTFOREF 0000000000033122 8-1 EQTY GB 21419 ACTUALS EUR000000000462098830 8738 N C70390000501F SQTY BUY 212102 49500.00# 9.34 8738 8738 "
var x= Sting.substring(1,27)
Result x= CREC 20
I don't want it like this, rather, I want my result to be
x= CREC 20
This is a browser thing - consecutive spaces are displayed as one. You might want to replace ' ' with and then it will display all spaces indiviudaly
x.replace(" ", " ");
Another way is to avoid displaying the string as HTML. For example the alert() function will show the correct number of spaces without the need to replace. Also displaying the string within a <pre> tag should work fine too.
I think Dobromir's interpretation of the OP is probably correct, and therefore a good answer.
If it is indeed a browser thing, then perhaps a better way to get it to display properly without changing the string itself is to style the HTML element with
white-space: pre
This will preserve the spaces like it does in a <pre> block.
See http://www.w3schools.com/cssref/pr_text_white-space.asp
If your spaces are always the same length you could do:
x.replace(" ", " ");
otherwise you can use a regular expression to replace multiple spaces with one:
x.replace(/\s+/g, ' ');
as seen Here
This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 9 years ago.
SITUATION
I started to implement the game "HANGMAN" using only JavaScript and HTML on client side machines. I have completed all the logical work. Now only the aesthetics are remaining. And I am stuck up because we can't write to strings in JS.
a = "abcd"; a[0] = "e"; -- This type of thing is not allowed.
What I have done
CODE
The code I have tried, This does not work:
See here
I now have the following three arrays:
a -- The array that contains the letters of the word(for gel this would be g,e,l)
gai -- This array consists of the letters that have been entered by the user and are there in the word.(like g or e)
ag -- This array consists of the letters that have been entered by the user regardless of whether or not they are there in the word to be guessed or not.
What I need to do
I need to generate the output that would show the letter in case it has been guessed by the user and is there in the word(letters in the array gai) and _ in place of letters that have not yet been entered by the user.
What I want
A function that will return the desired output, as explained in the following example.
Example
Let the word to be guessed be:
together
User enters e:
The function should return: _ _ _ e _ _ e _
User then enters d, my program will prompt him to say that this letter is not there in the word.
User enters r
Function should return: _ _ _ e _ _ e r
And so on....
I hope you get the idea!
In case you don't get it(owing to my bad explanation or otherwise!!)
You can play a game of hangman here: Hangman
Just watch the output at the bottom of the screen... Thats what I want this function to generate.
Kindly help me with this issue!
Reading just the start of your question (because no other code is provided), there is a problem which could be solved using native javascript functions.
var strarr = "Hello world!".split(''); // this will give you an array of characters to be manipulated
strarr[6] = "X"; // so you can do this
console.dir(strarr.join('')); // test it!
As an idea (not mine, its from comments) one could even wrap this simple code as a missing toCharArray() function and use that.
Another thing is that this method is fast enough even for relatively large bulk of text. For a test I used lorem ipsum with 1000 words. On my rather old dev machine, manipulation executes in milliseconds.
For more information, see this discussion.
Also you can use this function to set char at specified index of string:
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
You could use regex to mask letters in a word using String.replace.
var word = "together"
, correct = "";
function guess(c) {
if (word.indexOf(c) > -1) {
correct += c;
}
console.log(word.replace(new RegExp("[^" + correct + "]", "g"), "_"));
}
Using Ajax to fetch XML data. question about blank text nodes
I read this question/ answer here
Javascript/XML - Getting the node name
and this helped my understanding a ton about how the structure is set up however I still have a question or two.. when he mentions this part:
"Text node with a carriage return and some spaces or tab"
How would you test to see f you have gotten an empty text node like this? I've tried testing to see:
if nodeValue == null
nodeValue == "null"
nodeValue == ""
nodeValue == " "
none of these appear to be working
I figured maybe the length would be 0 so I tested for .length and it returned 5 (1 return key and 4 tabs.. added an extra tab in there and tested again it returned 6)
I then googled how to remove whitespace and used these:
.replace(/\s+/g, ' ');
.replace(/^\s+|\s+$/g, '');
Neither worked and still said the .length was still 5
Reason I want to test for this is because what if I don't know each of the element node names before hand or exactly how the DOM is set up.
Or is there a better way to navigate without bothering to check if a text node is just the tabs/spaces/return key?
.replace(/^\s+|\s+$/g, ''); works unless the spaces/tabs aren't really spaces and tabs, but one of the various other Unicode space-like characters. So I'm guessing you weren't quite using it correctly.
This would be how to use it:
if (!textNode.nodeValue.replace(/^\s+|\s+$/g, '')) {
// Node is empty
}
Example: Live Copy | Live Source
var xml = parseXml("<test>\n\t\t\t</test>");
var textNode = xml.documentElement.firstChild;
display("textNode.nodeValue.length = " +
textNode.nodeValue.length);
display('Is "empty"? ' +
(!textNode.nodeValue.replace(/^\s+|\s+$/g, '')));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Output:
textNode.nodeValue.length = 4
Is "empty"? true
(Where parseXML is from this answer.)
But we really don't need to do a replace (although the overhead of doing it is trivial). A test like this would do it:
if (/^\s*$/.test(textNode.nodeValue)) {
// The node is "empty"
}
That regular expression (zero or more whitespace characters with anchors at both ends) will only match a string that's already empty or consists only of whitespace characters.
I have an HTML page that I generate from the data contained in a database. The database sometimes contains long strings that the browser can't break because the strings don't contain breakable characters (space, point, comma, etc...).
Is there any way to fix this using html, css or even javascript?
See this link for an example of the problem.
Yes you can, just set the css property of the box to:
.some_selector {
word-wrap: break-word;
}
Edit: Some testing shows that it does work with a div or a p - a block level element - but it does not work with a table cell, nor when the div is put inside a table cell.
Tested and works in IE6, IE7, IE8, Firefox 3.5.3 and Chrome.
Works:
<div style="word-wrap: break-word">aaaaaaaaaaaaaaaaaaaaaaddddddddddddddddddddddddddddddddddddddddddaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa </div>
Based on this article and this one as well: the "Shy Hyphen" or "Soft Hyphen" can be written in HTML as: / / ­ (173 dec = AD hex). They all convert to the U+00AD character.
The JavaScript textContent and nodeValue of the DOM Text Nodes are not 'entity encoded' - they just contain the actual entities. In order to write these characters you must therefore encode them yourself: \xAD is a simple way to write the same character in a JavaScript string. String.fromCharCode(173) would also work.
Based on your own VERY good answer - a jQuery Plugin version:
$.fn.replaceInText = function(oldText, newText) {
// contents() gets all child dom nodes -- each lets us operate on them
this.contents().each(function() {
if (this.nodeType == 3) { // text node found, do the replacement
if (this.textContent) {
this.textContent = this.textContent.replace(oldText, newText);
} else { // support to IE
this.nodeValue = this.nodeValue.replace(oldText, newText);
}
} else {
// other types of nodes - scan them for same replace
$(this).replaceInText(oldText, newText);
}
});
return this;
};
$(function() {
$('div').replaceInText(/\w{10}/g, "$&\xAD");
});
A side note:
I think that the place this should happen is NOT in JavaScript - it should be in the server side code. If this is only a page used to display data- you could easily do a similar regexp replace on the text before it is sent to the browser. However the JavaScript solution offers one advantage(or disadvantage depending on how you want to look at it) - It doesn't add any extraneous characters to the data until the script executes, which means any robots crawling your HTML output for data wont see the shy hyphens. Although the HTML spec interprets it as a "hyphenation hint" and an invisible character its not guaranteed across the rest of the Unicode world: (quote from Unicode standard via the second article I linked)
U+00AD soft hyphen indicates a
hyphenation point, where a line-break
is preferred when a word is to be
hyphenated. Depending on the script,
the visible rendering of this
character when a line break occurs may
differ (for example, in some scripts
it is rendered as a hyphen -, while in
others it may be invisible).
Another Note:
Found in this other SO Question - it seems that the "Zero Width Space" character / / U+200b is another option you might want to explore. It would be \x20\x0b as a javascript string.
As it has been pointed out numerous times, no, there is nothing you can do about it, without preprocessing the strings programmatically before displaying them.
I know there is a strategy with inserting the soft hyphen character (), where needed, but does not seem like a popular option.
Check out this question: Soft hyphen in HTML ( vs. )
It is also possible to use word-break css property to cut every word on the element edge.
.selector_name {
word-break: break-all;
}
<p class="selector_name">some words some words some words some words</p>
you can obtain:
some word|
s some wo|<-edge of the element
rds some |
words som|
e words |
There is special character or that could do it.
For example:
Dzielenie wyrazów
could be display like:
1. dzie
2. le
3. nie wy
5. ra
6. zow
I'm answering my own question here...
Based on your answers, I came up with this solution (thanks to #CMS in this question for his help).
This script breaks any word that is more than 30 characters long by inserting a space at the 31st position.
Here is the fixed version: link
I have one problem left, I'd rather insert a then a space. But the assigning node.nodeValue or node.textContent causes the insertion of the text not the tag.
<script type="text/javascript">
$(function() {
replaceText(/\w{30}/g, "$& ", document.body);
});
function replaceText(oldText, newText, node) {
node = node || document.body; // base node
var childs = node.childNodes, i = 0;
while (node = childs[i]) {
if (node.nodeType == 3) { // text node found, do the replacement
if (node.textContent) {
node.textContent = node.textContent.replace(oldText, newText);
} else { // support to IE
node.nodeValue = node.nodeValue.replace(oldText, newText);
}
} else { // not a text mode, look forward
replaceText(oldText, newText, node);
}
i++;
}
}
</script>
I'll wait a few days before I accept this answer in case someone comes up with a simpler solution.
Thanks
The issue with using and the solutions above is that an extra character is still there, and with a copy/paste action (even in plain text) it comes out.
I would use instead the tag <wbr> that is not visible and is not considered when copying.
For example, to have email addresses break in two lines (only when there is not enough space) I use this:
echo str_replace( "#","<wbr>#", $email );
That results in something like this:
name.surname
#website.com
You can use jQuery to achieve that, but How : Let me explain a little bit. First you need to add the reference and there is a plug-in which may help you : Read More Plugin - JQuery But you need to penetrate your code during the fetch phase. At this point you can handle this problem in HttpHandler or Page_PreInit phase but w/o any server side code it must be hard or perhaps there isn't any way. I don't know but you should be able to add something in your database-fetched html page.
It's easier to break up the long words from a text string, before you add them to the document.
It would also be nice to avoid orphans, where you have only one or two characters on the last line.
This method will insert spaces in every unspaced run of characters longer than n,
splitting it so that there are at least min characters on the last line.
function breakwords(text, n, min){
var L= text.length;
n= n || 20;
min= min || 2;
while(L%n && L%n<min)--n;
var Rx= RegExp('(\\w{'+n+',}?)','g');
text= text.replace(Rx,'$1 ');
return text;
}
//test
var n=30, min=5;
var txt= 'abcdefghijklmnopqrstuvwxyz0123456789 abcdefghijklmnopqrstuvwxyz012345678 abcdefghijklmnopqrstuvwxyz01234567 abcdefghijklmnopqrstuvwxyz0123456';
txt=txt.replace(/(\w{30,})/g,function(w){return breakwords(w,n,min)});
alert(txt.replace(/ +/g,'\n'))
/* returned value: (String)
abcdefghijklmnopqrstuvwxyz0123
456789
abcdefghijklmnopqrstuvwxyz0123
45678
abcdefghijklmnopqrstuvwxyz012
34567
abcdefghijklmnopqrstuvwxyz01
23456
*/