Wrap each word in string with span using regular exp - javascript

how to replace each word in text with "span" using regular exp?
var text = "1:393 1:838 3:936 1:998 1:1398 1:1652 1:1718 1:1806"
final op = "<span class="word">1:393</span><span class="word">1:838</span><span class="word">3:936</span><span class="word">1:998</span><span class="word">1:139</span>...."

You don't really need a regex for that if the separator is always a single space, just split on the space (or \b if you want a regex), add some markup, and join back together again.
var text = "1:393 1:838 3:936 1:998 1:1398 1:1652 1:1718 1:1806";
var op = text.split(' ').map(function(w) {
return '<span class="word">' + w + '------</span>';
}).join('');
document.body.innerHTML = op;
.word {color : red}

var op = '<span class="word">' + text.split(' ').join('</span><span class="word">') + '</span>'

Using String#replace.
const text = "1:393 1:838 3:936 1:998 1:1398 1:1652 1:1718 1:1806";
const result = text.replace(/\d:\d+/g, '<span class="word">$&</span>');
console.log(result);

This is what you need (https://jsfiddle.net/6r005vgf/3/):
var text = "1:393 1:838 3:936 1:998 1:1398 1:1652 1:1718 1:1806";
//var final = "<span class='word'>1:393</span><span class='word'>1:838</span><span class='word'>3:936</span><span class='word'>1:998</span><span class='word'>1:139</span>....";
var final_test = "<span class='word'>" + text.replace(/\s+/g, "</span><span class='word'>") + "</span>";
//alert(final);
alert(final_test);

Related

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

Replace a few different elements in the string and return it

I have a string and I want change some words.
I write next function. If a word to change is alone in my string, this work normal. But if that words more then one it change only last.
<div class="container">
<div id="main-arr">How are you my friend?</div>
<div id="main-arr__last"></div>
</div>
$(document).ready(function() {
var sometext = $('#main-arr').text();
var someArr = sometext.split(' ');
for ( var i = 0; i < someArr.length; i++ ) {
if ( someArr[i] === 'you' || someArr[i] === 'he' || someArr[i] === 'she' ) {
var newArr1 = someArr.slice(0, i);
var newArr2 = someArr.slice(i + 1, someArr.length);
newArr1 = newArr1.join(' ');
newArr2 = newArr2.join(' ');
var word = 'error!';
console.log(newArr1);
console.log(newArr2);
$('#main-arr__last').html(newArr1 + '<span class="red">' + ' ' + word + ' ' + '</span>' + newArr2);
}
}
});
The function is not changing only the last word. The problem is that every time you replace a word you replace the html in #main-arr__last too.
Here is a better solution:
$(document).ready(function() {
var sometext = $('#main-arr').text();
sometext = replaceAll(sometext, ' you ', ' error! ');
sometext = replaceAll(sometext, ' he ', ' error! ');
sometext = replaceAll(sometext, ' she ', ' error! ');
var someHtml = toHtml(sometext, 'red');
$('#main-arr__last').html(someHtml);
});
function replaceAll(str, search, replacement){
return str.replace(new RegExp(search, 'g'), replacement);
}
function toHtml(str, clazz){
return replaceAll(str, 'error!', '<span class="' + clazz + '">error!</span>');
}
First we implement a function replaceAll to replace all occurrence of a word in a text, after that we have the text with all the words, you, he and she, in our case, replaced by error!.
Then we implemented the function toHtml to involve all 'error!' word in a span with a determined class passed as a parameter.

swapping in javascript without split

text left - text right
How to swap right to left using jquery? str pos is not so good because the parttern is not always fix. It could be somethingleft-somethingright
What's wrong with?:
var string = "text left - text right";
var newString = string.split("-").reverse().join(" - ");
var before = "text left - text right";
var separator = " - ";
var regex = new RegExp("(.*)(" + separator + ")(.*)");
var replace = "$3$2$1";
var after = before.replace(regex, replace);
document.write(after);
You may use String.replace() and RegExp for this task;
var swap = function(str) {
return str.replace(/(.*)(\s?\-\s?)(.*)/, '$3$2$1');
};
var str = 'Left - Right';
alert('Before is: ' + str);
alert('After is: ' + swap(str));
str = 'Apples-Mangoes';
alert('Before is: ' + str);
alert('After is: ' + swap(str));

correctly escaping characters when generating dynamic HTML

I have the following code in a jsFiddle:
function Start() {
var TheData = 'tes"ss<div></div>t3\'k';
var TheHTML = '<div class="SomeClass">' + TestXSS(TheData) + '</div>';
TheHTML += '<input type="text" id="TheTextBox" value="';
TheHTML += TestXSS(TheData) + '" />';
$('#Dynamic').html(TheHTML);
}
function TestXSS(TheText) {
TheText = TheText.replace('"', '"');
TheText = TheText.replace("'", ''');
TheText = TheText.replace('<', '<');
TheText = TheText.replace('>', '>');
return TheText;
}
As you can see, the HTML is dynamically generated and added to the DOM with jQuery, and there's also a function to escape characters that might cause problems. But in the fiddle, there's still an issue and so I was wondering how to correctly escape characters.
Thanks.
Try
function TestXSS(TheText) {
TheText = TheText.replace(/"/g, '"');
TheText = TheText.replace(/'/g, ''');
TheText = TheText.replace(/</g, '<');
TheText = TheText.replace(/>/g, '>');
return TheText;
}
Demo: Fiddle
TheText.replace('"', '"'); // stops after first match
use g modifier for global match
TheText = TheText.replace(/"/g, '"');
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).`
I'd suggest reducing the number of (unnecessary) calls to replace(), and using a regular expression in concert with a map:
function TestXSS(TheText) {
var charMap = {
39 : '&#39',
34 : '&quot',
60 : '<',
62 : '>'
}
return TheText.replace(new RegExp("['\"<>]",'g'), function(a){
return charMap[a.charCodeAt(0)] || '';
});
}
JS Fiddle demo.
References:
RegExp().
replace().

Javascript replace special chars { } "

Why does this code fail replacing the special chars:
http://jsfiddle.net/TTfzu/26/
var strOutput = 'aaa { " } ';
strOutput.replace(/{/g, "");
strOutput.replace(/}/g, "");
strOutput.replace(/"/g, "");
document.write( strOutput );
What needs to be changed?
replace doesn't change its argument, it returns a new string. You have to assign the result somewhere otherwise it's lost:
var strOutput = 'aaa { " } ';
strOutput = strOutput.replace(/{/g, "");
strOutput = strOutput.replace(/}/g, "");
strOutput = strOutput.replace(/"/g, "");
document.write( strOutput );
or just use a character class [...] in your regexp:
var strOutput = 'aaa { " } ';
strOutput = strOutput.replace(/[{}"]/g, "");
You will need to catch the result from the replace. (And you can chain your replaces.)
var strOutput = 'aaa { " } ';
strOutput = strOutput.replace(/{/g, "").replace(/}/g, "").replace(/"/g, "");
document.write( strOutput );
Btw you can make it as simple as this:
strOutput = strOutput..replace(/({|"|})/g, "");
As of #Alnitak comment:
strOutput = strOutput..replace(/[{}"]/g, "");
Per other answers, you need to use the result of .replace.
However you don't need three calls, you should be using:
strOutput = strOutput.replace(/[{}"]/g, '');
where the [...] is a character class which matches any individual character in that set. Within such a class the only characters that need to be escaped are ^-]\

Categories

Resources