I am getting error while Regex replace javascript - javascript

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);

Related

Issue with converting a function from ES6 to vanilla JavaScript to work in Internet Explorer

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.

Loop through text for multiple instances of same string

I have a passage of text, which might have multiple of the same word in it. Whenever this word appears, I want to replace it with itself, but wrapped in a div so that I can apply styles and add some extra text.
I have got this working for the first instance of the word:
var definition = glossaryList[index].definition;
var termStart = textAsLower.search(termAsLower);
var termEnd = term.length + termStart;
var replacedText = addDefinitionToText(textContent, term, definition, termStart, termEnd);
function addDefinitionToText(textContent, term, definition, termStart, termEnd) {
var textStart = textContent.substring(0, termStart);
var termInText = textContent.substring(termStart, termEnd);
var textEnd = textContent.substring(termEnd);
var replacedTerm = '<span class="has-definition">' + termInText;
replacedTerm += '<div class="attached-definition">';
replacedTerm += '<div class="defintion-title">' + term + '</div>';
replacedTerm += '<div class="definition-text">' + definition + '</div>';
replacedTerm += '</div>';
replacedTerm += '</span>';
return textStart + replacedTerm + textEnd;
}
I've tried putting this function into a while loop and counting up, but it is causing me issues and freezing or not returning what I am expecting:
while(something.toLowerCase().search(termAsLower)) {
var something = textAsLower.substring(termEnd);
termStart = something.search(termAsLower);
termEnd = term.length + termStart;
replacedText = addDefinitionToText(something, term, definition, termStart, termEnd);
something = replacedText.substring(termEnd);
}
Does anyone have a solution to this? Ideally I would actually like a different method to .search(), which finds all instances not just the first, but my searches haven't been too fruitful.
Thanks!
You can simply use regex to achieve what you want:
var searchWord = "tag";
var textStr = "HTML tag is used for scripting. Tag can also be self-closing.";
// case-insensitive regex
var re = new RegExp(searchWord, "gi");
textStr = textStr.replace(re, '<' + searchWord + '>');
// case-sensitive search
var re = new RegExp(searchWord, "g");
textStr = textStr.replace(re, '<' + searchWord + '>');
I did something like this before. I split the text by spaces and put that array into foreach and edit. Here's an exapmle code
if(text.includes("http")){
var returnString = '';
text.split(" ").forEach(function(link) {
if(link.includes("http")){
returnString += '<a target="_blank" style="color:white" href="' + link + '">here</a> ';
}else{
returnString += link + " ";
}
});
text = returnString;
A regular expression with the String replace method can solve this fairly easily.
This function will return a new string with the word and definition wrapped.
I have used a template literal to make things a bit cleaner but they are unsupported in IE.
function wrapWordWithDefinition(sentance, word, definition) {
var template = `<div>
<div class="attached-definition">
<div class="defintion-title">${word}</div>
<div class="definition-text">${definition}</div>
</div>
</div>`;
// global and case insensitive
var re = new RegExp(word, 'gi');
return sentance.replace(re, template);
}
var sentance = "This will replace word, when word is encountered";
var myword = "word";
var definition = "The definition of the word";
var result = wrapWordWithDefinition(sentance, myword, definition);
console.log(result)
For further reading on regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

How to find a particular value in a string in js

I have a data like this,
var str = "#data time #city";
My goal is to make this as
var str = <a src="www.test/data">#data</a> time <a src="www.test/city">city</a>
I mean in my string where ever I found # its next value i.e data should be set as a param to the link www.test/{{param}} and should be surrounded with a link.Can any one suggest help.Thanks.
For this case, the String.replace() function will help you:
var str = "#data time #city"
str = str.replace(/#(\S+)/g, '#$1')
output.textContent = str
clickable.innerHTML = str
#output { font-family: courier }
<div id="output"></div>
<div id="clickable"></div>
The following code converts you data to the expected output.
The document.write(..) are for debug.
var data='#data time #city';
var hashtags = data.match(/#\S+/g);
document.write('before: ' + data + '</br>');
for (j = 0; j < hashtags.length; j++) {
// remove # from hashtag
var tag = hashtags[j].substring(1, hashtags[j].length);
// create the link
var link = '< a src="www.test/' + tag + '>#' + tag + '< / a > ';
// replace hashtag with link
data=data.replace(hashtags[j], link);
}
document.write('after: ' + data);

Replace string in jquery is not working

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>

Add .html to a string Javascript?

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";

Categories

Resources