Replace the backslash with space in JavaScript - javascript

k = "hello'S";
var sym = k.replace(/\'/g,"\\'");
I want my output to look like: hello's
I am getting it now as hello\'s

From your comment (with various typos fixed):
var k = "hello's";
var sym =k.replace(/\'/g,'\\\'');
onclick = "gosymbol(\''+k+'\',event);
by doing this i am getting output as hello\'s but i wanted it to be like hello's
So what you're trying to do is embed a string in an onclick handler as text. That's not a good idea, not least because of the quoting hassles. Instead:
someElement.onclick = gosymbol.bind(someElement, k);
Live Example:
var k = "hello's";
var someElement = document.getElementById("some-element");
someElement.onclick = gosymbol.bind(someElement, k);
function gosymbol(arg, e) {
alert("gosymbol got: [" + arg + "], event type: " + e.type);
}
<div id="some-element">Click me</div>
If for some reason it has to be a string, then the problem is that you didn't have the right number of ' characters in your onclick line, and had k in the string literally (which means you weren't getting the output you described), and weren't using sym:
var k = "hello's";
var sym = k.replace(/'/g, "\\'");
onclick = "gosymbol('" + sym + "',event);";
I do not suggest doing that, but if that's what you want to do...
Live Example:
var someElement = document.getElementById("some-element");
var k = "hello's";
var sym = k.replace(/'/g, "\\'");
someElement.setAttribute("onclick", "gosymbol('" + sym + "',event);");
function gosymbol(arg, e) {
alert("gosymbol got: [" + arg + "], event type: " + e.type);
}
<div id="some-element">Click me</div>

Related

I am getting error while Regex replace 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);

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

javascript replace all is not working?

I have to replace all the special character form the html and i have created an array of special character having key value pairs of special characters and class name .
But this is not working . I have tried and the following is the code and fiddle link.
var SpClass = new Array();
SpClass["&"] = "ampClass";
function temp() {
var str = "";
var tempLen = SpClass.length;
var k = 0;
var htmlForRemoveChar = $("#test").html();
for (var splChar in SpClass) {
if (k > tempLen) {
$("#test").html(htmlForRemoveChar);
}
var tempChar = "/" + splChar + "/g";
alert(htmlForRemoveChar);
htmlForRemoveChar = htmlForRemoveChar.replace(tempChar, '<span class="specialChar "' + SpClass[splChar] + '"">W</span>');
alert(htmlForRemoveChar);
k++;
}
$("#test").html(htmlForRemoveChar);
}
<div id="test">this is test & i am doing testing</div>
<input type="button" onclick="temp();" value="Remove&">
http://jsfiddle.net/aps123/y4McS/1/
You just need to change this line:
var tempChar = "/" + splChar + "/g";
To:
var tempChar = new RegExp(splChar, 'g');
At present you're replacing a literal String, e.g. '/a/g'. If you need to dynamically create the contents of a regex then you need to use RegExp. If the contents is static then you can use a regex literal.
Try replacing replace(tempChar with replace(new RegExp(splChar, 'g').
It looks like you are using a string literal, not a regex literal. A regex literal is like this:
var x = /x/g;

Using a list position as a param to a function to pull certain data

function getList()
{
var string2 = "<img src='close.png' onclick='removeContent(3)'></img>" + "<h4>Survey Findings</h4>";
string2 = string2 + "<p>The 15 Largest lochs in Scotland by area area...</p>";
document.getElementById("box3text").innerHTML = string2;
var myList = document.getElementById("testList");
for(i=0;i<lochName.length;i++)
{
if(i<3)
{
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
else
{
var listElement = "Loch "+lochName[i];
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
}
}
This function generates a list with the 1st 3 elements being hyperlinks. When clicked they should call a function call getLoch(i) with i being the position of the item in the list. However when i pass it the value it just give it a value of 15, the full size of the array and not the position.
function getLoch(Val)
{
var str = "<img src='close.png' onclick='removeContent(4)'></img>" + "<h4>Loch " + lochName[Val] +"</h4>";
str = str + "<ul><li>Area:" + " " + area[Val] + " square miles</li>";
str = str + "<li>Max Depth:" + " " + maxDepth[Val] + " metres deep</li>";
str = str + "<li>County:" + " " + county[Val] + "</li></ul>";
document.getElementById("box4").innerHTML = str;
}
There are 2 errors in your code as far as I can see. The first is the way you create your link.
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
This will actually result in code like this:
<a href='javascript:getLoch(i)'>Loch name</a>
Passing a variable i is probably not what you intended, you want it to pass the value of i at the time your creating this link. This will do so:
var listElement = "<a href='javascript:getLoch(" + i + ")'>" + "Loch "+ lochName[i] + "</a>";
So why does your function get called with a value of 15, the length of your list? In your getList function, you accidently made the loop variable i a global. It's just missing a var in your loop head.
for(var i=0;i<lochName.length;i++)
After the loop finished, i has the value of the last iteration, which is your array's length minus 1. By making i a global, and having your javascript code in the links use i as parameter, getLoch got called with your array length all the time.

Categories

Resources