I am trying to replace a string with another string but that is not working for me. I brief I am trying to replace a smiley string with a smiley image, but that is not working. Please take a look at code and let me know what is wrong with it:
var comment ="Hello all how are you :)";
var emo = {'smile': ':)', 'tongue': ':P'};
$.each(emo,function(index,value) {
if(comment.contains(value)){
var emopiclink = 'http://www.abcdedif.com/emoticon/'+index+'.png';
var emopic = '<img src="'+emopiclink+'" hieght="20px" width="20px">';
comment.replace(value, emopic);
console.log(comment);
// alert("String Found");
}
});
You need to accept the returned value from replace() method and there is no contains use indexOf()
var comment = "Hello all how are you :)";
var emo = {
'smile': ':)',
'tongue': ':P'
};
$.each(emo, function(index, value) {
if (comment.indexOf(value) > -1) {
var emopiclink = 'http://www.abcdedif.com/emoticon/' + index + '.png';
var emopic = '<img src="' + emopiclink + '" hieght="20px" width="20px">';
comment = comment.replace(value, emopic);
console.log(comment);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
var newInput = '{"id":"1","value":"Admin","prefix":"#"} asdas {"id":"24","value":"Ibiere Banigo","prefix":"#"}';
var gettingJson = newInput.match(/\{\"(.*?)\"\}/g);
var finalString = '';
$.each(gettingJson, function (index, value) {
var data = JSON.parse(value);
finalString = newInput.replace(/\{\"(.*?)\"\}/g, '#[' + data.id + ']');
});
console.log(finalString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is my code I am trying to replace this the parenthesis with #[id] it is replacing it but for all like I want my output to be
#[1] someone new #[2]
but instead I am getting
#[2] someone new #[2]
Problem
The problem with your approach is the replace method replaces all matching occurrences.
Solution
Use replace method callback
replace(regexp, replacerFunction)
var newInput = '{"id":"1","value":"Admin","prefix":"#"} asdas {"id":"24","value":"Ibiere Banigo","prefix":"#"}';
var finalString = newInput.replace(/\{\"(.*?)\"\}/g, match => {
var data = JSON.parse(match);
return '#[' + data.id + ']'
})
console.log(finalString);
I created a Directory Search using regex to match the input to the data. I followed a tutorial for half of it and added to it on my own. It is working in Chrome, but not Internet Explorer.
I figured out this is due to ES6 incompatibilities in Internet Explorer and now I am having trouble figuring out how to correctly convert my displayMatches function to vanilla javascript or jQuery with no ES6.
So far most of it is working except that I can't figure how to remove the commas in in my html for the list of matches even though I tried using .join('')
Screenshot #1
Screenshot #2 - see the commas in between?
This is the working code on Chrome:
function displayMatches() {
// console.log(this.value);
$('.suggestions').show();
var matchArray = findMatches(this.value, employees);
console.log(matchArray);
var html = matchArray.slice(0,10).map(person => {
var regex = new RegExp(this.value, 'gi');
var firstName = person.GivenName.replace(regex, `<span class="hl">${this.value}</span>`);
var lastName = person.Surname.replace(regex, `<span class="hl">${this.value}</span>`);
var extension;
if (person.Phone_Ext1 !== null){
extension = person.Phone_Ext1;
} else {extension = "N/A"}
return `
<li class="search-item" data-id=${person.EmployeeID}>
<span class="person">${firstName} ${lastName}</span>
<span class="phone-ext">Ext. ${extension}</span>
</li>
`
}).join('');
if ($('#search-box').val() == ""){
suggestions.innerHTML = "";
} else {
suggestions.innerHTML = html;
}
}
And this is my attempt to convert:
function displayMatches() {
// console.log(this.value);
$('.suggestions').show();
var matchArray = findMatches(this.value, employees);
console.log(matchArray);
var html = [];
var person;
var list;
for(var i=0; i < matchArray.slice(0,10).length; i++){
person = matchArray.slice(0,10)[i];
var regex = new RegExp(this.value, 'gi');
var hilight = '<span class="hl">' + this.value + '</span>';
var firstName = person.GivenName.replace(regex, hilight);
var lastName = person.Surname.replace(regex, hilight);
var extension;
if (person.Phone_Ext1 !== null){
extension = person.Phone_Ext1;
} else {
extension = "N/A"
}
list =
'<li class="search-item" data-id=' + person.EmployeeID +'>' +
'<span class="person">' + firstName + ' ' + lastName + '</span>' +
'<span class="phone-ext">Ext. ' + extension + '</span>' +
'</li>';
html.push(list);
}
html.join('');
console.log(html);
if ($('#search-box').val() == ""){
suggestions.innerHTML = "";
} else {
suggestions.innerHTML = html;
}
}
html.join('') returns a new string. It doesn't transmogrify the array to a string, it doesn't assign a new value to the html variable. You would need to do
html = html.join('');
or even better use two separate variables, one of the array and one for the string.
Btw, you don't even need to construct and fill the array yourself in a loop, you can use the ES5 Array map method since IE9. As #H.B. remarked in the comments, you only need to use a function expression instead of the arrow syntax.
Here,
I am validating URL with following string which either it should be http/https or ip address along with query string and different parenthesis square bracket [] .
I want to prevent following url parenthesis
2)http://192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]Id] - Not Allowed
what should be regular expression to prevent [publisher[client_id]Id] sting ?
I'm using following regular expression for above strings
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex .test(str)) {
return false;
} else {
return true;
}
what should be changed code for same?
Please help me for the same.
Try this:
var strings = [
'[publisher[client_id]Id]',
'[publisher_id]'
];
var pattern = /\[.*\[.*\].*\]/;
strings.forEach(function(string){
if(pattern.test(string)) {
console.log(string + " -> matched");
}
else {
console.log(string + " -> not matched");
}
});
try this. the first group return url without parameter (withour your publiser, etc)
sorry didn't read it carefully. try that one and return true if valid
edited
var t1 = "htts:/192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]]";
var t2 = "https://192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192";
var t3 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]]";
var t4 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?name=[publisher[client_id]]";
var t5 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?foo=bar&name=[publisher[client_id]]";
function check(str) {
var url = /((http[s]?:\/\/){1,1}(\w+[-.\/]{0,1}\w?)*)/g,
p = /([\?\&](\w+=){0,1}\[\w+\[\w+\]\w*\])/g;
/*check for url*/
if (!url.test(str)) {
return "invalid url";
}
/*check for [userid[userid]]*/
return p.test(str) ? "invalid" : "valid";
}
document.body.innerHTML = check(t1) + "</br>";
document.body.innerHTML += check(t2) + "</br>";
document.body.innerHTML += check(t3) + "</br>";
document.body.innerHTML += check(t4) + "</br>";
document.body.innerHTML += check(t5) + "</br>";
regards
var pre = '<a href=someDirectoryPath';
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML = trailHTML + pre + getURL(trail[i]) + mid + trail[i] + post;
if(i!=(trail.length-1)) {
trailHTML += ' > ';
}
}
document.write(trailHTML);
trail is an arraylist of valid pages, like so:
['some name', 'another name','yet another name','name']
getURL just takes that name and adds a '-' in between words, which is the page name. This has been tested and works. (for example, getURL('some name') returns 'some-name')
The problem is, when run in IE9 (untested in other browsers), when I write trailHTML to the page, I only get the last element in the array. Why is this?
Let me know if you need any clarification...
function getURL(txt){
return txt.replace(/ /g,"-");
}
var trail = ['some name', 'another name','yet another name','name'];
///////////////////////////////////////////////////
var pre = '<a href="someDirectoryPath/'; // changed
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML += pre + getURL(trail[i]) + mid + trail[i] + post;
if(i<trail.length-1)trailHTML+=" > " // changed
}
document.write(trailHTML);
You have a syntax error in your for-loop: The open "{" on the if does not have a matching "}".
I ran a small sample in IE9 and got all items in the array, not just the last item as you report. Here's what I ran:
<script type="text/javascript">
function getURL(s){
return s.replace(" ", "-");
}
var trail = ['some name', 'another name','yet another name','name'];
var pre = '<a href=someDirectoryPath';
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML = trailHTML + pre + getURL(trail[i]) + mid + trail[i] + post;
if(i!=(trail.length-1)) {
trailHTML += " > ";
}
}
trailHTML = trailHTML + getURL(trail[0]);
document.write(trailHTML);
</script>
The output looked like this:
some name > another name > yet another name > namesome-name
Most likely your issue is caused by the syntax error, or in how the array is built/passed into your function.
I want to check if a string is ending with ".php" extension, if not I want to add .html at the end. I have already tried various "slice" methods without success.
You can use Regex for that
var string1 = "www.example.com/index";
var newString = !/\.php$/i.test(string1)? string1+".html": string1;
// newString = "www.example.com/index.html"
Use (yourstring + '.html').replace(/\.php\.html$/, '.php') to do that:
var str1 = 'one.php';
var str2 = 'two';
var str3 = '.php.three.php';
var str4 = '.php.hey';
console.log((str1 + '.html').replace(/\.php\.html$/, '.php')); // Prints one.php
console.log((str2 + '.html').replace(/\.php\.html$/, '.php')); // Prints two.html
console.log((str3 + '.html').replace(/\.php\.html$/, '.php')); // Prints .php.three.php
console.log((str4 + '.html').replace(/\.php\.html$/, '.php')); // Prints .php.hey.html
Or perhaps:
function appendHTML(string) {
var html = string;
if (string.lastIndexOf('.php') === (string.length - 4)) {
html += '.html';
}
return html;
}
Well, slice() works ok for this task.
var s = "myfile.php";
if (s.slice(-4) != ".php")
s = s.slice(0, -4) + ".html";
Use regular expression to solve your problem.
/.php$/ is a regular expression that checks to see if a string ends with '.php'
For more information read: http://www.w3schools.com/js/js_obj_regexp.asp
Example Code:
str = "http://abc.com";
str = ( /\.php$/.test( str ) ) ? str : str + '.html'; // this is the line you want.
str === "http://abc.com.html" // returns true
Try something like this
function isPHP(str)
{
return str.substring(str.length - 4) == ".php";
}
Then you could do
str = isPHP(str) ? str : str + ".html";