I have string that is stored in a variable in this form :
var c = "<p>Let's try with single inputs : *[]*</p>"
I can easily split and convert the *[]* into <span> using this method [a]:
var res = c.split("*[]*");
if(res.length > 1){
var strContent = res[0];
var inptSoal = ' <span id="content-input" class="al question mb-0">[ ]</span> ';
strContent += inptSoal;
strContent += res[1];
c = strContent;
} return c;
But now, let's say that i have this form of string [b] :
var c = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>"
How can i split (and convert) every *[ and ]* (that has strings inside of it) into HTML <span> element? Thanks in advance
EDIT
To make it clearer, using the method i write above ([a]) it will return this in my website :
What i want to do is to return the same result if the condition is like the second form ([b]) i mentioned above. How can i achieve this?
SOLVED ✅
Every answers here solved my problem. The first answer here was Ofek's answer. It works well, what i need to do to achieve the result i want is only to change the "<span>" + input + "</span>" inside the replace() function into :
"<span id='content-input' class='al question mb-0'>" + input + "</span>" to make the span element has the CSS Style like my screenshot above.
Other two answers, sid's answer and Rahul Kumar's answer also works well. But i prefer to choose Rahul Kumar's answer for its simplicity.
Thanks in advance to everyone that answered my questions!
Use regex to match the pattern and pass it to String.replace() method to replace the matched pattern in your string with new string <span>$1</span>. Here $1 indicates the captured group which is a content inside brackets *[...]*.
str = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>"
const regex = /\*\[(.*?)\]\*/g;
const finalStr = str.replace(regex, "<span>$1</span>");
console.log(finalStr);
You can use this method:
function replaceWithInput(str, replacer) {
var arr = str.split("*[");
for (var i = 1; i < arr.length; i++) {
var index = arr[i].indexOf("]*");
arr[i] = replacer(arr[i].slice(0, index)) + arr[i].slice(index + 2);
}
return arr.join("");
}
you use it like so:
function replace(input) {
return "<span>" + input + "</span>"
}
replaceWithInput("<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>", replace);
Using Regex you could do,
let c = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>";
let newC = c.replace(/\*([[])/g, '<span>');
let newC2 = newC.replace(/\]([*])/g, '</span>');
console.log(newC2);
I am using split function like this :
function getFirstPart(str) {
return str.split('/')[0];
}
function getSecondPart(str) {
return str.split('/')[1];
}
For first part it is working as expected, but for second part i want everything behind first /.
For example in /stub/787878/hello, I want stub as first part and /787878/hello as second part.
How to make pattern for such condition.
Instead of trying to use split, find the slash, and take the string to the left and right of it:
function divideAtSlash(str) {
const index = str.indexOf('/', 1);
return [str.slice(0, index), str.slice(index)];
}
The second argument (1) to indexOf tells it to start matching at the second character, because in this case we want to skip over the leading slash.
The first element of the returned tuple will be /stub, not stub. If you want the latter, then
return [str.slice(1, index), str.slice(index)];
This is what you are looking for:
const str = '/stub/787878/hello/911';
const [, firstPart, ...rest] = str.split('/');
const secondPart = '/' + rest.join('/')
console.log('first part: ', firstPart);
console.log('second part: ', secondPart);
i guess getSecondPart() is returning 787878 in your example.
you need to check how many parts you have in your arrayy after splitting the string and then return every part except the first.
function getSecondPart(str) {
var astr = str.split('/');
str = "";
for(var i = 0; i < astr.length; i++) {
str += "/" + astr[i];
}
return(str);
}
CODE IS NOT TESTED, I just want to give you an idea.
I am learning regex, and I got a doubt. Let's consider
var s = "YYYN[1-20]N[]NYY";
Now, I want to replace/insert the '1-8' between [ and ] at its second occurrence.
Then output should be
YYYN[1-20]N[1-8]NYY
For that I had tried using replace and passing a function through it as shown below:
var nth = 0;
s = s.replace(/\[([^)]+)\]/g, function(match, i, original) {
nth++;
return (nth === 1) ? "1-8" : match;
});
alert(s); // But It wont work
I think that regex is not matchIing the string that I am using.
How can I fix it?
You regex \[([^)]+)\] will not match empty square brackets since + requires at least 1 character other than ). I guess you wanted to write \[[^\]]*\].
Here is a fix for your solution:
var s = "YYYN[1-20]N[]NYY";
var nth = 0;
s = s.replace(/\[[^\]]*\]/g, function (match, i, original) {
nth++;
return (nth !== 1) ? "[1-8]" : match;
});
alert(s);
Here is another way of doing it:
var s = "YYYN[1-20]N[]NYY";
var nth = 0;
s = s.replace(/(.*)\[\]/, "$1[1-8]");
alert(s);
The regex (.*)\[\] matches and captures into Group 1 greedily as much text as possible (thus we get the last set of empty []), and then matches empty square brackets. Then we restore the text before [] with $1 backreference and add out string 1-8.
If it’s only two occurences of square brackets, then this will work:
/(.*\[.*?\].*\[).*?(\].*)/
This RegEx has “YYYN[1-20]N[” as the first capturing group and “]NYY” as the second.
I suggest using simple split and join operations:
var s = "YYYN[1-20]N[]NYY";
var arr = s.split(/\[/)
arr[2] = '1-8' + arr[2]
var r = arr.join('[')
//=> YYYN[1-20]N[1-8]NYY
You can use following regex :
var s = "YYYN[1-20]N[]NYY";
var nth = 0;
s = s.replace(/([^[]+\[(?:[^[]+)\][^[]+)\[[^[]+\](.+)/, "$1[1-8]$2");
alert(s);
The first part ([^[]+\[([^[]+)\][^[]+) will match a string contain first sub-string between []. and \[[^[]+\] would be the second one which you want and the last part (.+?) match the rest of your string.
So using jQuery, I'm trying to use an array to search through paragraph elements using an array and when it finds certain words it converts that word to a link with that class.
I'm trying to use this:
jQuery('.story').html(function(i,html) {
var w = ['ocean','waves','bed', 'swimming'];
$.each(w,function(i,w) {
html = html.replace(new RegExp('' + w + '', 'g'),w[i]);
});
return html;
});
jsfiddle
The end result would turn ocean into ocean et al.
But it doesn't seem to be working. I don't really understand why either. Thanks ahead of time.
m(_ _)m
_|7O
(The end plan is to have it so that those words play certain SFX when pressed and I'm basing off the class so when the word shows up again in the story it plays the same sound).
Like this?
var w = ['ocean','waves','bed', 'swimming'],
reg = new RegExp('(' + w.join('|') + ')','g');
jQuery('.story').html(function(_, curHtml) {
return curHtml.replace(reg,"<a href='#' class='$1'>$1</a>");
});
Demo
You need to use html instead of val and construct the regexp based on all the words so that they can be matched at once and replace the matched value with the string and using the match token, $1
How about?
var arr = ['ocean','waves','bed', 'swimming'];
var result = $('.story').text();
$.each(arr, function (i, val) {
result =
result.replace(val, '' + val + '');
});
$('.story').html(result);
http://jsfiddle.net/8XWf3/21/
There are a few issues with your code:
You use the same variable i and w twice. They override each other. Although that does not make a difference here
You use .val instead of .html. .val should only be used for form fields.
You swapped the reg exp and the replacement in the replace call
Try this:
jQuery('.story').html(function(i,val) {
var w = ['ocean','waves','bed', 'swimming'];
$.each(w, function(j,w) {
val = val.replace(new RegExp(w, 'g'), '' + w + '');
});
return val;
});
As an extra remark: doing it the way you set this up can get you into trouble if one of the words in the array is a substring of one of the other. Watch out for this.
var w = ['ocean','waves','bed', 'swimming'];
$.each(w,function(i,w) {
jQuery('.story').html(function(i,val) {
val = val.replace(w,'<a href="" class="' + w + '">' + w + '<\/a>');
return val;
});
});
JS FIDDLE: http://jsfiddle.net/8XWf3/22/
I need to replace every instance of '_' with a space, and every instance of '#' with nothing/empty.
var string = '#Please send_an_information_pack_to_the_following_address:';
I've tried this:
string.replace('#','').replace('_', ' ');
I don't really like chaining commands like this. Is there another way to do it in one?
Use the OR operator (|):
var str = '#this #is__ __#a test###__';
console.log(
str.replace(/#|_/g, '') // "this is a test"
)
You could also use a character class:
str.replace(/[#_]/g,'');
Fiddle
If you want to replace the hash with one thing and the underscore with another, then you will just have to chain
function allReplace(str, obj) {
for (const x in obj) {
str = str.replace(new RegExp(x, 'g'), obj[x]);
}
return str;
};
console.log(
allReplace( 'abcd-abcd', { 'a': 'h', 'b': 'o' } ) // 'hocd-hocd'
);
Why not chain, though? I see nothing wrong with that.
If you want to replace multiple characters you can call the String.prototype.replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.
For example, if you want a replaced with x, b with y, and c with z, you can do something like this:
const chars = {
'a': 'x',
'b': 'y',
'c': 'z'
};
let s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);
Output: 234xyz567yyyyxz
Chaining is cool, why dismiss it?
Anyway, here is another option in one replace:
string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})
The replace will choose "" if match=="#", " " if not.
[Update] For a more generic solution, you could store your replacement strings in an object:
var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})
Specify the /g (global) flag on the regular expression to replace all matches instead of just the first:
string.replace(/_/g, ' ').replace(/#/g, '')
To replace one character with one thing and a different character with something else, you can't really get around needing two separate calls to replace. You can abstract it into a function as Doorknob did, though I would probably have it take an object with old/new as key/value pairs instead of a flat array.
I don't know if how much this will help but I wanted to remove <b> and </b> from my string
so I used
mystring.replace('<b>',' ').replace('</b>','');
so basically if you want a limited number of character to be reduced and don't waste time this will be useful.
Multiple substrings can be replaced with a simple regular expression.
For example, we want to make the number (123) 456-7890 into 1234567890, we can do it as below.
var a = '(123) 456-7890';
var b = a.replace(/[() -]/g, '');
console.log(b); // results 1234567890
We can pass the substrings to be replaced between [] and the string to be used instead should be passed as the second parameter to the replace function.
Second Update
I have developed the following function to use in production, perhaps it can help someone else. It's basically a loop of the native's replaceAll Javascript function, it does not make use of regex:
function replaceMultiple(text, characters){
for (const [i, each] of characters.entries()) {
const previousChar = Object.keys(each);
const newChar = Object.values(each);
text = text.replaceAll(previousChar, newChar);
}
return text
}
Usage is very simple. Here's how it would look like using OP's example:
const text = '#Please send_an_information_pack_to_the_following_address:';
const characters = [
{
"#":""
},
{
"_":" "
},
]
const result = replaceMultiple(text, characters);
console.log(result); //'Please send an information pack to the following address:'
Update
You can now use replaceAll natively.
Outdated Answer
Here is another version using String Prototype. Enjoy!
String.prototype.replaceAll = function(obj) {
let finalString = '';
let word = this;
for (let each of word){
for (const o in obj){
const value = obj[o];
if (each == o){
each = value;
}
}
finalString += each;
}
return finalString;
};
'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"
You can just try this :
str.replace(/[.#]/g, 'replacechar');
this will replace .,- and # with your replacechar !
Please try:
replace multi string
var str = "http://www.abc.xyz.com";
str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"
replace multi chars
var str = "a.b.c.d,e,f,g,h";
str = str.replace(/[.,]/g, ''); //str is "abcdefgh";
Good luck!
Here's a simple way to do it without RegEx.You can prototype and/or cache things as desired.
// Example: translate( 'faded', 'abcdef', '123456' ) returns '61454'
function translate( s, sFrom, sTo ){
for ( var out = '', i = 0; i < s.length; i++ ){
out += sTo.charAt( sFrom.indexOf( s.charAt(i) ));
}
return out;
}
You could also try this :
function replaceStr(str, find, replace) {
for (var i = 0; i < find.length; i++) {
str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
}
return str;
}
var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);
console.log(text);
find refers to the text to be found and replace to the text to be replaced with
This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :
new RegExp(find[i], 'g')
You can also pass a RegExp object to the replace method like
var regexUnderscore = new RegExp("_", "g"); //indicates global match
var regexHash = new RegExp("#", "g");
string.replace(regexHash, "").replace(regexUnderscore, " ");
Javascript RegExp
yourstring = '#Please send_an_information_pack_to_the_following_address:';
replace '#' with '' and replace '_' with a space
var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');
newstring2 is your result
For replacing with nothing, tckmn's answer is the best.
If you need to replace with specific strings corresponding to the matches, here's a variation on Voicu's and Christophe's answers that avoids duplicating what's being matched, so that you don't have to remember to add new matches in two places:
const replacements = {
'’': "'",
'“': '"',
'”': '"',
'—': '---',
'–': '--',
};
const replacement_regex = new RegExp(Object
.keys(replacements)
// escape any regex literals found in the replacement keys:
.map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);
Here is a "safe HTML" function using a 'reduce' multiple replacement function (this function applies each replacement to the entire string, so dependencies among replacements are significant).
// Test:
document.write(SafeHTML('<div>\n\
x</div>'));
function SafeHTML(str)
{
const replacements = [
{'&':'&'},
{'<':'<'},
{'>':'>'},
{'"':'"'},
{"'":'''},
{'`':'`'},
{'\n':'<br>'},
{' ':' '}
];
return replaceManyStr(replacements,str);
} // HTMLToSafeHTML
function replaceManyStr(replacements,str)
{
return replacements.reduce((accum,t) => accum.replace(new RegExp(Object.keys(t)[0],'g'),t[Object.keys(t)[0]]),str);
}
String.prototype.replaceAll=function(obj,keydata='key'){
const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(new RegExp(`${keys[0]}${key}${keys[1]}`,'g'),val),this)
}
const data='hids dv sdc sd {yathin} {ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'{key}'))
This works for Yiddish other character's like NEKUDES
var string = "נׂקֹוַדֹּוֶת";
var string_norm = string.replace(/[ְֱֲֳִֵֶַָֹֹּׁׂ]/g, '');
document.getElementById("demo").innerHTML = (string_norm);
Not sure why nobody has offered this solution yet but I find it works quite nicely:
var string = '#Please send_an_information_pack_to_the_following_address:'
var placeholders = [
"_": " ",
"#": ""
]
for(var placeholder in placeholders){
while(string.indexOf(placeholder) > -1) {
string = string.replace(placeholder, placeholders[placeholder])
}
}
You can add as any placeholders as you like without having to update your function. Simple!
One function and one prototype function.
String.prototype.replaceAll = function (search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'gi'), replacement);
};
var map = {
'&': 'and ',
'[?]': '',
'/': '',
'#': '',
// '|': '#65 ',
// '[\]': '#66 ',
// '\\': '#67 ',
// '^': '#68 ',
'[?&]': ''
};
var map2 = [
{'&': 'and '},
{'[?]': ''},
{'/': ''},
{'#': ''},
{'[?&]': ''}
];
name = replaceAll2(name, map2);
name = replaceAll(name, map);
function replaceAll2(str, map) {
return replaceManyStr(map, str);
}
function replaceManyStr(replacements, str) {
return replacements.reduce((accum, t) => accum.replace(new RegExp(Object.keys(t)[0], 'g'), t[Object.keys(t)[0]]), str);
}
What if just use a shorthand of if else statement? makes it a one-liner.
const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );
Or option working fine for me
Example let sample_string = <strong>some words with html tag </strong> | . need to remove the strong tag and "|" text.
the code is like this = sample_string.replace(/\|(.*)|<strong>|<\/strong>/g,"")