Display only whole word using javascript - javascript

I have a text say "A sample text for testing". I need to display only ten characters in a div.
so i do substring on the text
txt.substring(0,10)
This gives me "A sample t". Since its ugly to display a unterminated word, i need only to display "A Sample" to be displayed. How do i do this?

You could do what you do, substringing the text to 10 chars.
Then you use txt.lastIndexOf(' ') to find the last space in the text.
Then you use that to substring the text again.
Example:
var txt = "A Sample Text";
txt = txt.subString(0,10); // "A Sample T"
txt = txt.subString(0, txt.lastIndexOf(' ')); // "A Sample"
Let me know if it helps!

Assuming that you'd rather have a cut off string than an empty string, if the word is longer than ten characters:
function shorten(txt)
{
// if it's short or a space appears after the first 10 characters, keep the substring (simple case)
if (txt.length <= 10 || txt[10] === ' ') return txt;
// get the index of the last space
var i = txt.substring(0, 11).lastIndexOf(' ');
// if a space is found, return the whole words at the start of the string;
// otherwise return just the first 10 characters
return txt.substring(0, i === -1 ? 11 : i);
}

use substring method to do this
i think you should add a filter to check whether the 11th character is space or not with the substring method. otherwise the last valid word too might removed. get "New sample text for testing" for example.
this is the code.
str = "A sample text for testing"
ch11_space = (str[10] == ' ') ? 0 : 1;
str = str.substring(0,10);
if (ch11_space) {
str = str.substring(0,str.lastIndexOf(' '));
}

function getShortenedString(str)
{
var maxLength = 10; // whatever the max string can be
var strLength = str.length;
var shortenedStr = str.substr(0, maxLength);
var shortenedStrLength = shortenedStr.length;
var lastSpace = str.lastIndexOf(" ");
if(shortenedStrLength != strLength)
{
// only need to do manipulation if we have a shortened name
var strDiff = strLength - shortenedStrLength;
var lastSpaceDiff = shortenedStrLength - lastSpace;
if(strDiff > lastSpaceDiff) // non-whole word after space
{
shortenedStr = str.substr(0, lastSpace);
}
}
return shortenedStr;
}

Related

How to replace new line character with comma in angular

I have one textarea field in which the user can enter input in a new line as well as comma-separated values. so when I m sending values in API /n is appended in case of the new line and same /n is visible on detail page which I don't want. below is the example of user input.
Ex-1
ABC
red
test,blue
Ex-2
abc,blue,
green,red
test
I want each time to check for new line break and comma, my mean is to say
if user enter values in new line then replace newline character with a comma and if a comma is already appended
then keep it as it is.
Expected output
Ex-1
ABC,red,test,blue
Ex-2
abc,blue,green,red,test
Below is my code
createData(data) {
const Obj = {};
if (data.enum && data.value_type === 'Enum') {
Obj['values'] = data.enum.split(',');
}
console.log(Obj,"constraint");
return Obj;
}
You need first split the string with a newline character, Remove any empty string from the array once it's done joined it with ,. Also, we need to take care of some double comma as string contain a comma.
var str = `ABC
red
test,blue`;
var str2 = `abc,blue,
green,red
test`;
formateString(str);
formateString(str2);
function formateString(str) {
var strArray = str.split("\n");
strArray = strArray.filter((item) => {
return item !== '';
});
console.log(strArray.join(",").split(",,").join(","));
}
Using regex split()
Regex Demo
const str1 = `ABC
red
test,blue`;
const str2 = `abc,blue,
green,red
test`;
console.log(str1.split(/[,\n]+\s+/g).join(','))
console.log(str2.split(/[,\n]+\s+/g).join(','))
Another approach is to intercept input every time user enters character. With this method you avoid parsing whole text over and over again with every keystroke (including redundant ones).
Following is a simple piece of code that substitutes newlines and spaces with commas on the fly. Assuming you have a textarea with id textArea somewhere in your HTML.
const textArea = document.getElementById('textArea');
const parseText = function parseText(e) {
if (e.keyCode === 13 || e.keyCode === 32) {
e && e.preventDefault();
let text = textArea.value;
let curStart = textArea.selectionStart;
let curEnd = textArea.selectionEnd;
if (curStart == text.length && curEnd == text.length && !text.endsWith(',')) {
text += ',';
textArea.value = text;
}
}
}
textArea.addEventListener('keydown', parseText);
Regards

New line break every two words in javascript string

I have one string
string = "example string is cool and you're great for helping out"
I want to insert a line break every two words so it returns this:
string = 'example string \n
is cool \n
and you're \n
great for \n
helping out'
I am working with variables and cannot manually do this. I need a function that can take this string and handle it for me.
Thanks!!
You can use replace method of string.
(.*?\s.*?\s)
.*?- Match anything except new line. lazy mode.
\s - Match a space character.
let string = "example string is cool and you're great for helping out"
console.log(string.replace(/(.*?\s.*?\s)/g, '$1'+'\n'))
I would use this regular expression: (\S+\s*){1,2}:
var string = "example string is cool and you're great for helping out";
var result = string.replace(/(\S+\s*){1,2}/g, "$&\n");
console.log(result);
First, split the list into an array array = str.split(" ") and initialize an empty string var newstring = "". Now, loop through all of the array items and add everything back into the string with the line breaks array.forEach(function(e, i) {newstring += e + " "; if((i + 1) % 2 = 0) {newstring += "\n "};})
In the end, you should have:
array = str.split(" ");
var newstring = "";
array.forEach(function(e, i) {
newstring += e + " ";
if((i + 1) % 2 = 0) {
newstring += "\n ";
}
})
newstring is the string with the line breaks!
let str = "example string is cool and you're great for helping out" ;
function everyTwo(str){
return str
.split(" ") // find spaces and make array from string
.map((item, idx) => idx % 2 === 0 ? item : item + "\n") // add line break to every second word
.join(" ") // make string from array
}
console.log(
everyTwo(str)
)
output => example string
is cool
and you're
great for
helping out

Split and replace text by two rules (regex)

I trying to split text by two rules:
Split by whitespace
Split words greater than 5 symbols into two separate words like (aaaaawww into aaaaa- and www)
I create regex that can detect this rules (https://regex101.com/r/fyskB3/2) but can't understand how to make both rules work in (text.split(/REGEX/)
Currently regex - (([\s]+)|(\w{5})(?=\w))
For example initial text is hello i am markopollo and result should look like ['hello', 'i', 'am', 'marko-', 'pollo']
It would probably be easier to use .match: match up to 5 characters that aren't whitespace:
const str = 'wqerweirj ioqwejr qiwejrio jqoiwejr qwer qwer';
console.log(
str.match(/[^ ]{1,5}/g)
)
My approach would be to process the string before splitting (I'm a big fan of RegEx):
1- Search and replace all the 5 consecutive non-last characters with \1-.
The pattern (\w{5}\B) will do the trick, \w{5} will match 5 exact characters and \B will match only if the last character is not the ending character of the word.
2- Split the string by spaces.
var text = "hello123467891234 i am markopollo";
var regex = /(\w{5}\B)/g;
var processedText = text.replace(regex, "$1- ");
var result = processedText.split(" ");
console.log(result)
Hope it helps!
Something like this should work:
const str = "hello i am markopollo";
const words = str.split(/\s+/);
const CHUNK_SIZE=5;
const out = [];
for(const word of words) {
if(word.length > CHUNK_SIZE) {
let chunks = chunkSubstr(word,CHUNK_SIZE);
let last = chunks.pop();
out.push(...chunks.map(c => c + '-'),last);
} else {
out.push(word);
}
}
console.log(out);
// credit: https://stackoverflow.com/a/29202760/65387
function chunkSubstr(str, size) {
const numChunks = Math.ceil(str.length / size)
const chunks = new Array(numChunks)
for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
chunks[i] = str.substr(o, size)
}
return chunks
}
i.e., first split the string into words on spaces, and then find words longer than 5 chars and 'chunk' them. I popped off the last chunk to avoid adding a - to it, but there might be a more efficient way if you patch chunkSubstr instead.
regex.split doesn't work so well because it will basically remove those items from the output. In your case, it appears you want to strip the whitespace but keep the words, so splitting on both won't work.
Uses the regex expression of #CertainPerformance = [^\s]{1,5}, then apply regex.exec, finally loop all matches to reach the goal.
Like below demo:
const str = 'wqerweirj ioqwejr qiwejrio jqoiwejr qwer qwer'
let regex1 = RegExp('[^ ]{1,5}', 'g')
function customSplit(targetString, regexExpress) {
let result = []
let matchItem = null
while ((matchItem = regexExpress.exec(targetString)) !== null) {
result.push(
matchItem[0] + (
matchItem[0].length === 5 && targetString[regexExpress.lastIndex] && targetString[regexExpress.lastIndex] !== ' '
? '-' : '')
)
}
return result
}
console.log(customSplit(str, regex1))
console.log(customSplit('hello i am markopollo', regex1))

Split sentence by space mixed up my index

I'm facing some problem while trying to send text to some spelling API.
The API return the corrections based on the words index, for example:
sentence:
"hello hoow are youu"
So the API index the words by numbers like that and return the correction based on that index:
0 1 2 3
hello hoow are youu
API Response that tell me which words to correct:
1: how
3: you
On the code I using split command to break the sentence into words array so I will be able to replace the misspelled words by their index.
string.split(" ");
My problem is that the API trim multiple spaces between words into one space, and by doing that the API words index not match my index. (I would like to preserve the spaces on the final output)
Example of the problem, sentence with 4 spaces between words:
Hello howw are youu?
0 1 2 3 4 5 6 7
hello hoow are youu
I thought about looping the words array and determine if the element is word or space and then create something new array like that:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
That way I could replace the misspelled words easily and than rebuild the sentence back with join command but the problem but the problem that I cannot use non-numeric indexes (its mixed up the order of the array)
Any idea how I can keep the formatting (spaces) but still correct the words?
Thanks
in that case you have very simple solution:L
$(document).ready(function(){
var OriginalSentence="howw are you?"
var ModifiedSentence="";
var splitstring=OriginalSentence.split(' ')
$.each(splitstring,function(i,v){
if(v!="")
{
//pass this word to your api and appedn it to sentance
ModifiedSentence+=APIRETURNVALUE//api return corrected value;
}
else{
ModifiedSentence+=v;
}
});
alert(ModifiedSentence);
});
Please review this one:
For string manipulation like this, I would highly recommend you to use Regex
Use online regex editor for faster try and error like here https://regex101.com/.
here I use /\w+/g to match every words if you want to ignore 1 or two words we can use /\w{2,}/g or something like that.
var str = "Hello howw are youu?";
var re = /\w+/g
var words = str.match(re);
console.log("Returning valus")
words.forEach(function(word, index) {
console.log(index + " -> " + word);
})
Correction
Just realize that you need to keep spacing as it is, please try this one:
I used your approach to change all to space. create array for its modified version then send to your API (I dunno that part). Then get returned data from API, reconvert it back to its original formating string.
var ori = `asdkhaskd asdkjaskdjaksjd askdjaksdjalsd a ksjdhaksjdhasd asdjkhaskdas`;
function replaceMeArr(str, match, replace) {
var s = str,
reg = match || /\s/g,
rep = replace || ` space `;
return s.replace(reg, rep).split(/\s/g);
}
function replaceMeStr(arr, match, replace) {
var a = arr.join(" "),
reg = match || /\sspace\s/g,
rep = replace || " ";
return a.replace(reg, rep);
}
console.log(`ori1: ${ori}`);
//can use it like this
var modified = replaceMeArr(ori);
console.log(`modi: ${modified.join(' ')}`);
//put it back
var original = replaceMeStr(modified);
console.log(`ori2: ${original}`);
Updated
var str = "Hello howw are youu?";
var words = str.split(" ");
// Getting an array without spaces/empty values
// send it to your API call
var requestArray = words.filter(function(word){
if (word) {
return word;
}
});
console.log("\nAPI Response that tell me which words to correct:");
console.log("6: how\n8: you");
var response = {
"1": "how",
"3": "you"
}
//As you have corrected words index, Replace those words in your "requestArray"
for (var key in response) {
requestArray[key] = response[key];
}
//now we have array of non-empty & correct spelled words. we need to put back empty (space's) value back in between this array
var count = 0;
words.forEach(function(word, index){
if (word) {
words[index] = requestArray[count];
count++;
}
})
console.log(words);
Correct me, if i was wrong.
Hope this helps :)
Try this JSFiddle
, Happy coding :)
//
// ReplaceMisspelledWords
//
// Created by Hilal Baig on 21/11/16.
// Copyright © 2016 Baigapps. All rights reserved.
//
var preservedArray = new Array();
var splitArray = new Array();
/*Word Object to preserve my misspeled words indexes*/
function preservedObject(pIndex, nIndex, title) {
this.originalIndex = pIndex;
this.apiIndex = nIndex;
this.title = title;
}
/*Preserving misspeled words indexes in preservedArray*/
function savePreserveIndexes(str) {
splitArray = str.split(" ");
//console.log(splitArray);
var x = 0;
for (var i = 0; i < splitArray.length; i++) {
if (splitArray[i].length > 0) {
var word = new preservedObject(i, x, splitArray[i]);
preservedArray.push(word);
x++;
}
}
};
function replaceMisspelled(resp) {
for (var key in resp) {
for (var i = 0; i < preservedArray.length; i++) {
wObj = preservedArray[i];
if (wObj.apiIndex == key) {
wObj.title = resp[key];
splitArray[wObj.originalIndex] = resp[key];
}
}
}
//console.log(preservedArray);
return correctedSentence = splitArray.join(" ");
}
/*Your input string to be corrected*/
str = "Hello howw are youu";
console.log(str);
savePreserveIndexes(str);
/*API Response in json of corrected words*/
var apiResponse = '{"1":"how","3":"you" }';
resp = JSON.parse(apiResponse);
//console.log(resp);
/*Replace misspelled words by corrected*/
console.log(replaceMisspelled(resp)); //Your solution

javascript/jquery shortening a string without cutting word off

say i had the string text = "this is a long string i cant display" i want to trim it down to 10 characters but if it doesnt end with a space finish the word i don't want the string variable to look like this "this is a long string i cant dis" i want it to finish the word until a space occurs. I'm trying this which was suggested by other people but .replace doesn't seem to be working but .length does? I read somewhere that javascript functions don't work inside jquery functions but i still don't understand why .length works
$(document).ready(function(){
$('.article').each(function(index){
var text = $(this).children('p').text()
var maxLength = 6;
var url = $(this).find('.article-link').attr('href');
alert(text.replace(/^(.{1}[^\s]*).*/, "$1"));
var trimmedString = text.substr(0, maxLength);
var text = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
//var text = text.substring(0, 80);
//text = text.replace(/^(.{10}[^\s]*).*/, "$1");
});
});
Seo duit, a chara:
var str = "The rain in Spain falls mainly on the plain.";
var l = 10;
while (str.length > l && str.substr(l-1,1) != " ") l++;
alert(str.substr(0,l));
Javascript functions most definitely do work inside jQuery functions. It looks like your regex might be the issue, if the replace function isn't working for you.
This code works:
$(document).ready(function() {
$('.article').each(function(index) {
var text = $(this).children('p').text();
var maxLength = 6;
var reg = new RegExp('^(.{' + maxLength + '}[^\\s]*).*');
alert(text.replace(reg, "$1"));
});
});
Here's a working example

Categories

Resources