replace symbol-number to gif - javascript

I need your help.
Here I have text: hello #005 goodbye.
How to make js replace text starting with # by img like <img src=/img/005.gif> if number (005<120)? I must have something like hello <img src=/img/005.gif> goodbye

In two steps to show process
var str = "hello #005 goodbye",
num = str.match(/\#(\d+) /)[1],
gif = '<img src="/img/'+num+'.gif" />';
console.log(str.replace("#"+num,gif));
One step - test for 3 digits too
var str = "hello #005 goodbye"
.replace(/\#(\d{3})/,'<img src="/img/$1.gif" />');
console.log(str);
With test:
function addGif(str) {
var num = str.match(/\#(\d+)/),
gif = num &&
num.length > 0 &&
parseInt(num[1]) >= 5 &&
parseInt(num[1]) <= 120 ? '<img src="/img/' + num[1] + '.gif" />' : "";
return gif ? str.replace("#" + num[1], gif) : "no number or number not in range";
}
var str = "hello # goodbye"; // will not return a match
console.log(addGif(str))
str = "hello #" // will not return a match
console.log(addGif(str))
str = "hello #005" // will return a match
console.log(addGif(str))
str = "hello #1005" // will not return a match
console.log(addGif(str))
str = "hello #100" // will return a match
console.log(addGif(str))
str = "hello #1111111111 goodbye" // will not return a match
console.log(addGif(str))

Makes no sense to do it in two steps when you can do it in one. The capture group in replace is $1 so you put that where you want the number to go.
var str = "hello #005 goodbye",
result = str.replace(/#(\d+)/,'<img src="/img/$1.gif" />');
console.log(result);
With a check inside the replace with the number requirement I missed the 2 times I read the question!
var str = "hello #005 goodbye",
result = str.replace(/#(\d{3})/, function (x, group1) {
var num = parseInt(group1);
return num >= 5 && num<=120 ? '<img src="/img/' + group1 + '.gif" />' : group1;
});
console.log(result);

Related

Line count shows 1 eventhough input field has no value

I am using below code to calculate words, characters and lines.
function wordCount( val ){
var wom = val.match(/\S+/g);
return {
charactersNoSpaces : val.replace(/\s+/g, '').length,
characters : val.length,
words : wom ? wom.length : 0,
lines : val.split(/\r*\n/).length
};
}
var textarea = document.getElementById("text");
var result = document.getElementById("result");
textarea.addEventListener("input", function(){
var v = wordCount( this.value );
result.innerHTML = (
"<br>Characters (no spaces): "+ v.charactersNoSpaces +
"<br>Characters (and spaces): "+ v.characters +
"<br>Words: "+ v.words +
"<br>Lines: "+ v.lines
);
}, false);
<textarea id="text"></textarea>
<div id="result"></div>
initially everything is set to zero. When we type it counts well. But when we clear the textbox, Lines shows value as 1 eventhough there is no texts in the textbox. How to make the line count zero?
I realized that splitting val make the length of it 1 even if it's empty:
// val is empty and it length is null
// But after splitting it would be one
val.split(/\r*\n/).length // 1
function wordCount( val ){
var wom = val.match(/\S+/g);
return {
charactersNoSpaces : val.replace(/\s+/g, '').length,
characters : val.length,
words : wom ? wom.length : 0,
lines : val.length ? val.split(/\r*\n/).length : val.length
};
}
var textarea = document.getElementById("text");
var result = document.getElementById("result");
textarea.addEventListener("input", function(){
var v = wordCount( this.value );
result.innerHTML = (
"<br>Characters (no spaces): "+ v.charactersNoSpaces +
"<br>Characters (and spaces): "+ v.characters +
"<br>Words: "+ v.words +
"<br>Lines: "+ v.lines
);
}, false);
<textarea id="text"></textarea>
<div id="result"></div>
If you split an empty string, the result is [""] -- an array with one element that's an empty string.
You can check for this case first with a conditional expression.
Also, there's no need to use \r* in the split delimiter, as it doesn't influence the count.
function wordCount( val ){
var wom = val.match(/\S+/g);
return {
charactersNoSpaces : val.replace(/\s+/g, '').length,
characters : val.length,
words : wom ? wom.length : 0,
lines : val.length == 0 ? 0 : val.split('\n').length
};
}
var textarea = document.getElementById("text");
var result = document.getElementById("result");
textarea.addEventListener("input", function(){
var v = wordCount( this.value );
result.innerHTML = (
"<br>Characters (no spaces): "+ v.charactersNoSpaces +
"<br>Characters (and spaces): "+ v.characters +
"<br>Words: "+ v.words +
"<br>Lines: "+ v.lines
);
}, false);
<textarea id="text"></textarea>
<div id="result"></div>
When a string is split, if none of the delimiters match, you'll be left with the original string.
const foo = 'foo';
console.log(foo.split(/bar/).length);
The same is true of the empty string - when split on, it'll still give you [''], which has a length..
You might match lines which have at least one character on them instead of splitting, thereby excluding empty lines.
lines: (val.match(/^./gm) || []).length

How to put the first letter capitalized and the rest lowercase?

1) I'm trying to apply the first letter in uppercase and the other as lowercase. If the user write in the input, it should automatically transform. Examples:
"isaac guilherme araújo" to "Isaac Guilherme Araújo"
"iSAAC guILHErme aRAÚJO" to "Isaac Guilherme Araújo"
2) In Brazil there are names with connectives.
Examples: "das" "da" "dos" "do" "de" "e".
Carlos Eduardo Julio dos Santos
Carlos Eduardo dos Santos e Silva
Carlos Eduardo da Silva
3) I am having this problem to work with the name fields. With the following code, i could apply the first letter in uppercase, but the others as lowercase i couldn't. Then, according to problem number 2, if I write:
value entered: "douglas de oliveira júnior"
should be: "Douglas de Oliveira Júnior"
shouldn't: "douglas de Oliveira Júnior". //value shown with current code
function contains(str, search){
if(str.indexOf(search) >= 0){
return true;
} else {
return false;
}
}
$.fn.capitalize = function(str) {
$.each(this, function() {
var split = this.value.split(' ');
for (var i = 0, len = split.length; i < len; i++) {
var verify = (split[len - 1] == "D" || split[len - 1] == "d") && (str == "e" || str == "E") || (str == "o" || str == "O");
if (verify == false) {
if ( contains(split[i], 'de') == false && contains(split[i], 'do') == false) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
}
}
}
this.value = split.join(' ');
});
return this;
};
$(".capitalize").keypress(function(e) {
var str = String.fromCharCode(e.which);
$(this).capitalize(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">
I'm a new member here on Stackoverflow and I apologize for the mistakes, I am learning javascript. Thank you!
This solution also fixes connectives in uppercase, such as carlos DE silva.
Try it with the snippet below :)
var connectives = {
das: true,
da: true,
dos: true,
do: true,
de: true,
e: true
};
function capitalize(str) {
return str
.split(" ")
.map(function(word) {
return !connectives[word.toLowerCase()]
? word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
: word.toLowerCase();
})
.join(" ");
};
$(".capitalize").keyup(function() {
var cursorStart = this.selectionStart;
var cursorEnd = this.selectionEnd;
var capitalizedString = capitalize($(this).val());
$(this).val(capitalizedString);
this.setSelectionRange(cursorStart, cursorEnd);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">
You could use a format function that capitalizes all words except those provided in a whitelist. Then format the input value whenever the user presses a key (doesn't work well if the user moves the input cursor around though):
function format(string, noCapList=[]) {
const words = string.toLowerCase().split(' ');
return words.map((word) => {
if(!word.length || noCapList.includes(word)) {
return word;
} else {
return word[0].toUpperCase() + word.slice(1);
}
}).join(' ');
}
const input = document.querySelector('input');
input.addEventListener('keyup', () => {
input.value = format(input.value, ["das", "da", "dos", "do", "de", "e"]);
});
<input/>
It looks like the issue with your code is in how you're formatting the input. I'm not 100% sure I understood the question, but this format function provides the output you were looking for.
for simplicity I used npm lodash
https://lodash.com/docs/4.17.11#capitalize
const _ = require('lodash');
const connectives = {
das: true,
da: true,
dos: true,
do: true,
de: true,
e: true
};
const nameToCapitalize = str.split(' ').map(word => connectives[word] ?
word.toLowercase : _.capitalize(word)).join(' ');
SimpleJ's answer is right, but to clarify your original approach: the "problem" is in the contains function - it actually does what it should according to it's name and returns true if the str contains search, so contains('douglas', 'do') === true; you already have the string split into separate words so just use split[i] !== "de" && split[i] !== "do" instead of the contains calls.
I have posted algorithm in FCC about title casing a sentence . Might it would help you!
function titleCase(str) {
//First Converted to lowercase in case of test cases are tricky ones
var spl=str.toLowerCase();
//Then Splitted in one word format as leaving one space as ' '
spl = spl.split(' ');
for(var i=0;i<spl.length;i++){
//Again Splitting done to split one letter from that respective word
var spl2= spl[i].split('');
// In specific word's letter looping has to be done in order to
// convert 0th index character to uppercase
for(var j=0;j<spl2.length;j++){
spl2[0]= spl2[0].toUpperCase();
}
// Then Joined Those letters to form into word again
spl[i] = spl2.join('');
}
// Then joined those words to form string
str = spl.join(' ');
return str;
}
titleCase("sHoRt AnD sToUt");
I found something that apparently was satisfactory. It even works when the user places the cursor in the middle of the input. I found it here:
Link - Stackoverflow
Can anyone here evaluate and tell me if have some problem with this code from the user Doglas?
function ucfirst (str) {
// discuss at: http://locutus.io/php/ucfirst/
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
var not_capitalize = ['de', 'da', 'do', 'das', 'dos', 'e'];
$.fn.maskOwnName = function(pos) {
$(this).keypress(function(e){
if(e.altKey || e.ctrlKey)
return;
var new_char = String.fromCharCode(e.which).toLowerCase();
if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
var start = this.selectionStart, end = this.selectionEnd;
if(e.keyCode == 8){
if(start == end)
start--;
new_char = '';
}
var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
var maxlength = this.getAttribute('maxlength');
var words = new_value.split(' ');
start += new_char.length;
end = start;
if(maxlength === null || new_value.length <= maxlength)
e.preventDefault();
else
return;
for (var i = 0; i < words.length; i++){
words[i] = words[i].toLowerCase();
if(not_capitalize.indexOf(words[i]) == -1)
words[i] = ucfirst(words[i]);
}
this.value = words.join(' ');
this.setSelectionRange(start, end);
}
});
$.fn.maskLowerName = function(pos) {
$(this).css('text-transform', 'lowercase').bind('blur change', function(){
this.value = this.value.toLowerCase();
});
};
$.fn.maskUpperName = function(pos) {
$(this).css('text-transform', 'uppercase').bind('blur change', function(){
this.value = this.value.toUpperCase();
});
};
};
$('.capitalize').maskOwnName();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">

how to replace all special characters except for spaces, . and brackets using java script

I am trying to replace all the special characters in a form in BPM.
I have used
replace(/[_\W]+/g, "-")
but this replaces all including .,() and spaces. I need to exclude some of these characters from being replaced
this is what i am trying to do in BPM
tw.local.sql="insert into BPM_RBD_GATEWAY values ('Forwarded','"+tw.local.RBDG.ProcessID+"','"+tw.local.RBDG.SolID+"','"+tw.local.RBDG.BranchCode+"','"+tw.local.RBDG.BranchName.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Name_brwr.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Name_Cooblgnt.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.CustID_Exstng.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.D_Status_Loan.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.D_Internl_Crdt_Ratng+"','"+tw.local.RBDG.D_Scheme_ProdctType.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Acnt_Nmbr.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Loan_Amnt.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Bal_Outstandng.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Sanctnd_Period.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Deviatns_loan_sanctnIfany.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.D_Loan_Sourcng+"','"+tw.local.RBDG.Prevs_Rate_concsn.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.D_Existng_Accnt_Type+"','"+tw.local.RBDG.Existing_acnt_Rate.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Recomndr_Rate.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Arrears_Inspctn_Comnts.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.D_Borwr_Source_Empl_Profsn.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Borwr_Source_Details.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_prmry_Nature.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_prmry_Value.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_prmry_DtlsLimit.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_Collatrl_Nature.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_Collatrl_Value.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_Collatrl_DetLimt.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Deatils_ExistngBus_BrwrEnjoy.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Deatils_ExistngBus_TotGroup.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Deatils_ExistngBus_OprtvAccnt.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Deatils_ExistngBus_OtherPrdct.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Additional_Details.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Specific_BrRecom.replace(/[_\W]+/g, "-")+"','','','','','','','','','','','','','','','','','"+tw.local.RBDG.Br_Entry_User+"','"+tw.local.RBDG.Recomndr_Entry_User+"','','','','','','','','','"+tw.local.RBDG.Date+"','','','','','','','')";
Use replacer function to filter out matches which you don't want to replace
var excludes = [",", " ", "(", ")"];
var output = input.replace(/[_\W]/g, function(match){
if ( excludes.indexOf(match) == -1 )
{
match = "-";
}
return match;
}) ;
DEMO
var input = "asda<>*(*_()(), wdsf %^&%^&";
var excludes = [",", " ", "(", ")"];
var output = input.replace(/[_\W]/g, function(match){
if ( excludes.indexOf(match) == -1 )
{
match = "-";
}
return match;
}) ;
alert(output);
var str = "ABC/D A.b.c.;Qwerty(dgdf)";
var result = str.replace(/[^A-Za-z.;()]/g, "");
You'll end up with ABCDA.b.c.;Qwerty(dgdf)
Tell me if that worked out well for you

Removing a range starting occurrence with specified place

I need to define the text area to delete from 4th occurrence of (_) and preserve the extension.
before 12_345_678_900_xxxxxxxxxxxxxxx.jpg after 12_345_678_900.jpg,
before 34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg
after 34_567_890_123.jpg
Is it possible?
One solution is to find the nth occurence and then use substring.
var one='12_345_678_900_xxxxxxxxxxxxxxx.jpg'; // 12_345_678_900.jpg
function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;
if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);
if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}
console.log(one.substring(0,nth_occurrence(one,'_',4))+one.substring(one.indexOf('.')));
Sure, split by "_" and then join back the data you want:
var str = "12_345_678_900_xxxxxxxxxxxxxxx.jpg";
str = str.split("_").slice(0,4).join("_") + "."+ str.split(".").slice(-1)
console.log(str)
Regular Expressions are great for this sort of scenario:
const data1 = '12_345_678_900_xxxxxxxxxxxxxxx.jpg'
const data2 = '34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg'
const re = /^([^_]+_[^_]+_[^_]+_[^_]+).*(.jpg)$/;
var test1 = data1.replace(re, '$1$2');
var test2 = data2.replace(re, '$1$2');
Try it out: https://jsfiddle.net/648xt3qq/
There are probably a few different regular expression approaches that would get the job done
Maybe this works for you:
function clean() {
var el = document.getElementById('area');
el.value = el.value.replace(/^(.*?_.*?_.*?_.*?)(_.*?)(\..*?.*)$/gmi, '$1$3');
}
<form action="">
<textarea cols="50" rows="4" id="area">12_345_678_900_xxxxxxxxxxxxxxx.jpg
34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg</textarea><br />
<input type="submit" onclick="clean(); return false;" />
</form>

how to get selected text surrounding context in javascript in different paragraph?

hi I have a few problems:
What might I get the word around the word selected, if the word before and after the selected word given limits only 20 words that surround the selected word?
how to get the correct position if the word in a paragraph have the same word, for example I have a sentence like this: foo laa foo doo then I choose the word "foo" whose position is in between the words laa and doo?
how to get word from a different paragraph?
for example:
p1 : I like the red shirt
p2: my mother did not like the red shirt
the word I selected is "mother", and I have to take 10 words around the word "mother" that is "I like the red dress" and "I do not like the red shirt."
notes:
question No. 2 is able to use the nextSibling and previousSibling?
this is my code i try :
<html>
<head>
<script type="text/javascript">
function getElements(){
var x = document.getElementsByTagName("body");
x = x[0].innerHTML;
x = x.replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";});
var str = x.replace(/<\/?[^>]+(>|$)/g, "");
var emailPattern = /[_a-zA-Z0-9\.]+#[\.a-zA-Z0-9]+\.[a-zA-Z]+/gi;
var urlPattern = /[a-z]+:\/\/[^\s]+/gi;
var numberOrSymbolPattern = /[0-9\.,!##\$%\^\&*\(\)`~_\-=\+|\\{}\[\]\s:;<>\?\/]+/gi;
//////alert(str);
var str = str.replace(emailPattern , " ");
var str = str.replace(urlPattern , " ");
var str = str.replace(numberOrSymbolPattern , " ");
//////alert(str);
var str = str.replace(/[\n\f\r\t]/g, " ");
var hilangtandabaca = str.replace(/[.!:;'",?]/g," ");
var kataptg = hilangtandabaca;
//alert(kataptg);
var kata = new Array();
kata[0] = " is ";
kata[1] = " the ";
kata[3] = " of ";
kata[4] = " a ";
kata[5] = " or ";
kata[6] = " for ";
kata[7] = " from ";
kata[8] = " in ";
kata[9] = " this ";
kata[10] = " and ";
kata[11] = " on ";
kata[12] = " with ";
kata[13] = " my ";
for(var i=0,regex; i<kata.length; i++){
var regex = new RegExp(kata[i],"gi");
kataptg = kataptg.replace(regex," ");
}
var select = getSelected()+ "";
alert(select);
var index = kataptg.indexOf(select);
//alert("indeks select text:" + index);
if (index >= 0) {
var strBefore = "";
var strAfter = "";
//var strOri ="";
//if (index = -1)
//strOri = kataptg.substr(index);
//alert(strOri);
if (index > 0)
strBefore = kataptg.substr(0, index);
//alert(strBefore);
if (index < kataptg.length - 1)
strAfter = kataptg.substr(index + select.length, kataptg.length - (index + select.length));
//alert(strAfter);
alert("Before: " + strBefore + "\nAfter: " + strAfter);
}
}
function getSelected() {
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
} else if (document.selection) {
userSelection = document.selection.createRange();
}
return userSelection;
}
</script>
</head>
<body>
<h2>About</h2>
<p> my email : a#a.a
<p> my url http://id.wikipedia.org/wiki/URL
<p> my telepon number = 081330782
<p>okey In agriculture, the harvest is the process of gathering mature crops from the fields. Reaping is the cutting of grain or pulse for harvest, typically using a scythe, sickle, or reaper.[1] The harvest marks the end of the growing season, or the growing cycle for a particular crop, and this is the focus of seasonal celebrations of on many religions. On smaller farms with minimal mechanization, harvesting is the most labor-intensive activity of the growing season great yeah. !:;'",?</p>
<p>
<input type="button" onclick="getElements()" value="ambil select text" />
</p>
</body>
</html>
This is a perfect example of JavaScript's innerHTML and split() methods. You can loop through the content of all of the p elements. Here's an example of searching in the first paragraph:
contentArray = document.getElementByTagName('p')[0].innerHTML.split(' ')
split(' ') splits the content of the element into an array, separating by the spaces. innerHTML is self explanatory.
Now, to find your words. indexOf() is your friend in this case:
foodex = contentArray.indexOf('foo');
alert('The first occurrence of the string \'foo\' in the text is at word number ' + foodex);
Finally, to get surrounding words, just play with the array (this won't work if the occurrence of the string is close to the start or end of the paragraph, namely less than 10 words away:
alert('I am the 10th word after \'foo\'' + contentArray[foodex + 10 - 1]);
Good luck (no guarantees this code works out of the box)!

Categories