Tomer
Tomer

Reputation: 17930

How to splice a string to uneven parts in javascript

I have an input field that has autocomplete on it (custom made autocomplete).

When the user types a word, the matching phrase should appear but the word the user typed should have a different color.

So if for example I have the string like "Hello World" and the user types "ll", He should get a list of matching phrases that contain "ll" but the "ll" should have different color.

So i need a way to splice "Hello World" so i'll get : ["he","ll","o World"] and then i can wrap "ll" with <span> and style it.

Upvotes: 1

Views: 233

Answers (4)

georg
georg

Reputation: 214959

The trick here is not to use regular expressions because they're going to fail if the replacement string contains a regex special character, like a dot or braces. Therefore, just pass the string as is to replace:

str = 'Hello Hello World'
sub = 'll'
result = str.replace(sub, '<span>$&</span>')

Note that this replaces only the first occurrence of sub if there are many, but that's probably how you want it.

Upvotes: 1

Adil
Adil

Reputation: 148130

You can use replace

strhtml.replace (/yourstrToSearch/g, '<span class="cl">' + 'yourstrToSearch' + '</span >');

Edit:

yourstrToSearch = "ll";
var regex = new RegExp( yourstrToSearch, "gi");
$('#div1').html($('#div1').html().replace(regex, '<span class="cl">' + yourstrToSearch + '</span >'));

Live Demo

Upvotes: 5

WTK
WTK

Reputation: 16971

Forget about splitting the string. In this case it's much easier to replace match (ll in your example) with span like so:

'Hello World'.replace(/(ll)/g, '<span>$1</span>');

Or even better, if you'd like for each ll in text to have different styles you can pass function to replace function like so:

var i = 0;
'Hello Hello World'.replace(/(ll)/g, function(match) {
    i++;
    return '<span class="highlight-'+i+'">'+match+'</span>;
});

// above returns - you can style highlight-1 .. n so each of them have different color
'He<span class="highlight-1">ll</span>o He<span class="highlight-2">ll</span>o World'

Upvotes: 2

VisioN
VisioN

Reputation: 145408

One possible regex solution:

var part = "ll";
"Hello World".match(new RegExp("^(.*)(" + part + ")(.*)$")).slice(1);
// >> ["He", "ll", "o World"]

Upvotes: 3

Related Questions